Why vectorlt;boolgt;::reference doesn#39;t return reference to bool?(为什么 vectorlt;boolgt;::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++(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 的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 vector<bool>::reference 不返回对 bool 的引用?


基础教程推荐
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 这个宏可以转换成函数吗? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09