为什么vector< bool> :: reference不返回bool的引用? [英] Why vector<bool>::reference doesn't return reference to bool?

查看:137
本文介绍了为什么vector< bool> :: reference不返回bool的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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 ++编译像这样:

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

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

问题是为什么会发生这种情况? 向量< bool> :: 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? :)

推荐答案

Vector专门用于bool

它被认为是std的一个错误。改用向量< char>

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...>;






有时您可能需要引用包含在矢量。不幸的是,使用向量< char> 只能提供chars的引用。如果您确实需要 bool& ,请查看 Boost Containers库。它有一个非特殊版本的向量< bool>


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>.

这篇关于为什么vector&lt; bool&gt; :: reference不返回bool的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆