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 的引用?


基础教程推荐
- 从 std::cin 读取密码 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01