San*_*ahu 13 c++ dictionary stdmap std c++-standard-library
我std::map在这里写了一个小程序,如下所示.
int main()
{
map<int,float>m1;
m1.insert(pair<int,float>(10,15.0)); //step-1
m1.insert(pair<float,int>(12.0,13)); //step-2
cout<<"map size="<<m1.size()<<endl; //step -3
Run Code Online (Sandbox Code Playgroud)
我创建了一个地图,其中int类型为键,浮点类型为地图m1的值(键 - 值)对
创建一个普通的int-float对并插入到map中.
创建了一个cross float-int对并插入到map中.现在我知道隐式转换正在使这对插入映射.
在这里,我只是不希望发生隐式转换,并且应该给出编译器错误.
在我们尝试执行step-2类型操作时,我必须在此程序/映射中进行哪些更改才能使comipiler标记出错?
这是一个建议:
template <typename K, typename V, typename W>
void map_insert(map<K,V>& m, K k, W w) {
V v = w;
m.insert(pair<K,V>(k,v));
}
int main() {
map<int,float>m1;
map_insert(m1, 10, 15.0);
map_insert(m1, 12.0, 13); // compiler complains here
cout<<"map size="<<m1.size()<<endl;
Run Code Online (Sandbox Code Playgroud)
第三个模板参数有点尴尬但是必须允许从中double转换float.
| 归档时间: |
|
| 查看次数: |
825 次 |
| 最近记录: |