强制std::map的键类型不能为const
force key type of a std::map not to be const
c++参考告诉我们std::map
typedef pair<const Key, T> value_type;
是否可以强制键类型不为const ?我需要在模板方法中这样做,比如
template<class T> // T represent a map in general (std::map, boost::unordered_map or whatever..)
void foo(const T& m)
{
typename T::value_type::first_type x;
x=0; // Wrong because x is const ...
}
不,它不是。
这是因为map根据键执行内部排序。如果你能自己修改钥匙,不管你愿不愿意,一切都会乱成一团。
你应该使用提供的API函数;如果使用一个导致改变一个Key值(实际上我不认为有任何改变),则可能发生适当的内部重新排序。
考虑getter和setter,以及它们在提供混乱/危险的直接成员访问的替代方法中的用途。
但是,你可以这样写:
template<class T>
void foo(const T& m)
{
typename T::key_type x;
x = 0;
}
std::map
类型别名
key_type Key
mapped_type T
value_type pair<const Key,T>
key_compare Compare
value_compare Nested class to compare elements
allocator_type Allocator
reference Allocator::reference
const_reference Allocator::const_reference
iterator Bidirectional iterator
const_iterator Constant bidirectional iterator
size_type Unsigned integral type (usually same as size_t)
difference_type Signed integral type (usually same as ptrdiff_t)
pointer Allocator::pointer
const_pointer Allocator::const_pointer
reverse_iterator reverse_iterator<iterator>
const_reverse_iterator reverse_iterator<const_iterator>
typename T::key_type
将为您提供键类型,而无需添加const
限定符。
前面的答案应该足以回答你的简单问题。作为一种更通用的方法,您可以使用boost::remove_const(来自boost type_traits)来移除类型的const限定符。
template<class T> // T represent a map in general (std::map, boost::unordered_map or whatever..)
void foo(const T& m)
{
typedef typename T::value_type::first_type X; //is const
typedef typename boost::remove_const<X>::type NonConstX;
NonConstX x;
x=0;
}
键类型必须为const。如果确定不会改变映射的顺序,则可以抛弃迭代器的const-ness。如果你弄错了,这可能会导致丑陋的bug。
相关文章:
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 不能将 "void *" 类型的值分配给类型 "TCHAR" 的实体
- 需要帮助在 c++ 中将字符串转换为字符 ----错误 "const char *" 类型的值不能用于初始化 "char" 类型的实体
- 为什么 int 类型的枚举类值不能用作 int
- 声明C++具有动态大小的数组类型在 Linux 中工作正常,但不能在 Windows 中工作
- 类型为 "Bucket&"(未限定的 const 限定)的引用不能使用 "SortedList." 类型的值进行初始化 如何修复此错误?
- 为什么"具有常量成员的结构"类型的指针不能指向"具有非常量成员的结构"?
- 为什么函数名不能与返回名类型相同?
- 运算符'<'不能应用于类型 'string' 和 'string' 的操作数
- 为什么我不能在运算符=中使用引用类型?
- "const wchar_t *" 类型的值不能用于初始化类型 "const PWSTR" 的实体
- Visual Studio C++:不能使用类型为 "const wchar_t *" 的值来初始化类型为 "TCHAR *" 的实体
- 不能使这种类型的"void(C::* volatile)(int) const "在参考手册C++示
- 为什么我不能在不进行任何转换的情况下将浮点数放入任何类型的 ptr 中?
- 为什么带有指针子对象的文字类类型的 constexpr 表达式不能是非类型模板参数
- 受保护的嵌套结构不能用作派生外部类中的返回类型?
- 不能将 "void *" 类型的值分配给类型 "RANDOMSTRUCT *" 的实体
- 为什么std::{container}::template不能推导其参数类型
- 为什么不能在C++中重新定义类中的类型名称?