C++引用告诉我们一个std :: map
typedef pair<const Key, T> value_type;
Run Code Online (Sandbox Code Playgroud)
是否可以强制键类型不是常量?我需要在模板方法中这样做
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 ...
}
Run Code Online (Sandbox Code Playgroud)
Lig*_*ica 15
不,这不对.
这是因为map基于键执行其内部排序.如果你可以自己修改钥匙,不管怎么说,一切都会破裂.
您应该使用提供的API函数; 使用一个导致更改Key值(实际上我认为没有做任何事情),可能会发生适当的内部重新排序.
想想getter和setter,以及它们在提供凌乱/危险的直接成员访问的替代方案中的用途.
但是,你可以这样写:
template<class T>
void foo(const T& m)
{
typename T::key_type x;
x = 0;
}
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2497 次 |
| 最近记录: |