const类型容器的const_iterator类型
const_iterator type of a container of const types
如果我编译以下代码:
#include <list>
using iter_t = std::list<const unsigned>::const_iterator;
int main(int, char**) {
return 0;
}
我得到以下编译错误:
In file included from /usr/local/Cellar/gcc/4.9.2_1/include/c++/4.9.2/x86_64-apple-darwin13.4.0/bits/c++allocator.h:33:0,
from /usr/local/Cellar/gcc/4.9.2_1/include/c++/4.9.2/bits/allocator.h:46,
from /usr/local/Cellar/gcc/4.9.2_1/include/c++/4.9.2/list:61,
from main.cpp:1:
/usr/local/Cellar/gcc/4.9.2_1/include/c++/4.9.2/ext/new_allocator.h: In instantiation of 'class __gnu_cxx::new_allocator<const unsigned int>':
/usr/local/Cellar/gcc/4.9.2_1/include/c++/4.9.2/bits/allocator.h:92:11: required from 'class std::allocator<const unsigned int>'
/usr/local/Cellar/gcc/4.9.2_1/include/c++/4.9.2/bits/stl_list.h:315:9: required from 'class std::_List_base<const unsigned int, std::allocator<const unsigned int> >'
/usr/local/Cellar/gcc/4.9.2_1/include/c++/4.9.2/bits/stl_list.h:447:11: required from 'class std::list<const unsigned int>'
main.cpp:3:41: required from here
/usr/local/Cellar/gcc/4.9.2_1/include/c++/4.9.2/ext/new_allocator.h:93:7: error: 'const _Tp* __gnu_cxx::new_allocator<_Tp>::address(__gnu_cxx::new_allocator<_Tp>::const_reference) const [with _Tp = const unsigned int; __gnu_cxx::new_allocator<_Tp>::const_pointer = const unsigned int*; __gnu_cxx::new_allocator<_Tp>::const_reference = const unsigned int&]' cannot be overloaded
address(const_reference __x) const _GLIBCXX_NOEXCEPT
^
/usr/local/Cellar/gcc/4.9.2_1/include/c++/4.9.2/ext/new_allocator.h:89:7: error: with '_Tp* __gnu_cxx::new_allocator<_Tp>::address(__gnu_cxx::new_allocator<_Tp>::reference) const [with _Tp = const unsigned int; __gnu_cxx::new_allocator<_Tp>::pointer = const unsigned int*; __gnu_cxx::new_allocator<_Tp>::reference = const unsigned int&]'
address(reference __x) const _GLIBCXX_NOEXCEPT
^
如果将容器类型从std::list
更改为std::vector
、std::deque
或std::forward_list
,则会得到大致相同的错误消息。如果我将模板参数从const unsigned
更改为unsigned
,它编译得很好。
这是怎么回事?我不明白为什么它不能编译。
Visual C++2015提供了明确的诊断
"C++标准禁止
const
元素的容器,因为allocator<const T>
格式不正确。
allocate
方法返回一个指向未初始化的T
项数组的指针,如果T
是const
,则这些项永远无法初始化allocator<const T>
格式错误的明确声明,所以这可能是语义的结果正如Dieter Lücking在评论中指出的那样,在提供reference
和const_reference
地址的两个成员函数之间,const
类型T
存在直接冲突,因为当类型为const
时,这两个函数是相等的。
相关文章:
- 在函数中使用运算符重载,在 c++ 中使用 const 类型输入参数
- 成员函数的"this"参数具有"const"类型,但我的函数实际上不是"const"
- 将 const 类型引用对象注册为类成员对象C++
- 为什么不能在模板函数中向局部变量添加低级 const 类型
- 对于 const 类型,没有可行的重载运算符 []
- 为什么在auto和template函数的情况下,类型都没有推导为"const"类型
- 如何在OOP C 中使用const类型类
- 特征矩阵const类型
- 如何在静态方法中返回const类型
- const类型容器的const_iterator类型
- C++:当返回类成员变量的地址时,编译器强制其为const *类型
- 类型绑定引用中的限定符和 const 类型的初始值设定项中删除
- 在 main 中初始化类的 "static const" 类型变量成员的更好方法
- 正在检查是否有const类型
- 为什么我们能够在类定义中定义[static const int],而不能定义其他静态const类型
- 了解一些涉及 const 类型的C++代码
- c++ 11中的const类型转换为const别名
- 为什么将const类型的智能指针强制转换为类型的智能指针有效?
- STL:为"const T &"类型调用带有ptr_fun的 bind2nd
- 我应该什么时候传递"T* const&"类型的指针?