-1

我正在尝试编写一个包含位数组(作为成员变量)的 C++ 模板类。位数组的大小在编译时是已知的,所以我真的很希望它是 a std::bitset,但是我很难编写一个operator[]函数来设置位。

例如,我希望我的班级开始这样的事情:

template<size_t N>
class bitvector
{
public:
    bool operator[](size_t i) const { return bits[i]; }
    bool& operator[](size_t i) { return bits[i]; }
private:
    std::bitset<N> bits;
};

吸气剂工作正常。问题是std::bitset::operator[]setter 函数返回 a std::bitset::reference(不是 a bool&),它本身是模板化的。我对模板不太熟悉,但以下尝试失败了:

template<size_t K>
std::bitset<K>::reference operator[](size_t i) { return bits[i]; }

出现以下错误need 'typename' before 'std::bitset<K>::reference' because 'std::bitset<K>' is a dependent scope。我尝试了一些谷歌搜索,但无济于事。

std::bitset适合这项任务的工具吗?如果是这样,我该如何编写setter函数?如果没有,我可以用什么代替?(我仍然希望它实际上存储为位,并且std::vector<bool>看起来不太正确,因为我希望在编译时严格固定数组大小)。

4

1 回答 1

3

您可以std::bitset<N>::reference按如下方式返回:

template<size_t N>
class bitvector
{
public:
    bool operator[](size_t i) const { return bits[i]; }
    typename std::bitset<N>::reference operator[](size_t i) { return bits[i]; }
private:
    std::bitset<N> bits;
};

不需要额外的template<size_t K>,因为您仍然可以访问原始模板参数 N,并且在任何情况下您都不希望 N 和您的 K 不同。

您需要typename在函数的返回类型之前告诉编译器这::reference是一个类型而不是一个值。

例如:

struct Foo{
   typedef int reference;
};

struct Bar{
    static int reference;
};

Here Foo::reference is a type, but Bar::reference is a variable, without the typename before the return type the compiler will complain as it could be that std::bitset<N>::reference is a variable. (The compiler should have all the information it needs to work out that it isn't a value, but for some reason it is required anyway).

于 2016-04-12T21:14:42.943 回答