问题描述
#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 不是 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>.
这篇关于为什么 vector<bool>::reference 不返回对 bool 的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)