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 的引用?
基础教程推荐
- 提升 ASIO 流缓冲 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- c++ STL设置差异 2022-01-01
