为什么 vector<bool>::reference 不返回对 bool 的引用?

2021-12-31 00:00:00 compiler-errors g++ c++
#include <vector>

struct A
{
    void foo(){}
};

template< typename T >
void callIfToggled( bool v1, bool &v2, T & t )
{
    if ( v1 != v2 )
    {
        v2 = v1;
        t.foo();
    }
}

int main()
{
    std::vector< bool > v= { false, true, false };

    const bool f = false;
    A a;

    callIfToggled( f, v[0], a );
    callIfToggled( f, v[1], a );
    callIfToggled( f, v[2], a );
}

上面例子的编译产生了下一个错误:

The compilation of the example above produces next error :

dk2.cpp: In function 'int main()':
dk2.cpp:29:28: error: no matching function for call to 'callIfToggled(const bool&, std::vector<bool>::reference, A&)'
dk2.cpp:29:28: note: candidate is:
dk2.cpp:13:6: note: template<class T> void callIfToggled(bool, bool&, T&)

我像这样使用 g++(4.6.1 版)编译:

I compiled using g++ (version 4.6.1) like this :

g++ -O3 -std=c++0x -Wall -Wextra -pedantic dk2.cpp

问题是为什么会这样?vector::reference 不是 bool& 吗?还是编译器的错误?
或者,我在尝试一些愚蠢的事情吗?:)

The question is why this happens? Is vector<bool>::reference not bool&? Or is it a compiler's bug?
Or, am I trying something stupid? :)

推荐答案

向量专用于 bool.

这被认为是标准错误.使用 vector 代替:

It is considered a mistake of the std. Use vector<char> instead:

template<typename t>
struct foo {
  using type = t;
};
template<>
struct foo<bool> {
  using type = char;
};

template<typename t, typename... p>
using fixed_vector = std::vector<typename foo<t>::type, p...>;

<小时>

有时您可能需要引用包含在向量中的布尔值.不幸的是,使用 vector 只能为您提供对字符的引用.如果您确实需要 bool&,请查看 提升容器库.它有一个非特殊版本的 vector.


Occasionally you may need references to a bool contained inside the vector. Unfortunately, using vector<char> can only give you references to chars. If you really need bool&, check out the Boost Containers library. It has an unspecialized version of vector<bool>.

相关文章