std::map, std::unordered_map - 初始化列表中的缩小转换

Ale*_*xBG 7 c++ stdmap c++17

它是错误还是标准允许?

#include <iostream>
#include <map>
#include <unordered_map>

int main() {
    std::unordered_map<int,int> mm {{44,44}, {33.3, 54}, {222.2,222.2}};
    for(auto& [f,s] :mm) {
        std::cout<<f<<" - "<<s<<std::endl;
    }

    std::map<int,int> m {{44,44}, {33.3, 54}, {222.2,222.2}};
    for(auto& [f,s] :m) {
       std::cout<<f<<" - "<<s<<std::endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

在wandbox.org 上使用 clang10 和 gcc10对其进行测试。std::set和没有这样的问题std::unordered_set。

son*_*yao 8

的元素类型std::map和std::unordered_map是std::pair。问题是std::pair有一个模板化的构造函数,

template< class U1, class U2 >
constexpr pair( U1&& x, U2&& y );
Run Code Online (Sandbox Code Playgroud)

初始化first与std::forward<U1>(x)和second用 std::forward<U2>(y)。

例如,给定{33.3, 54},U1被推导为double并且U2被推导为int,请注意这是一个完全匹配并且不需要转换来使用此构造函数来构造std::pair,然后也不会发生收缩转换。

另一方面,对于std::set,给定std::set<int> s {33.3};,将使用std::settake的构造函数std::initializer_list<int>,并且从std::initializer_list<int>初始化{33.3},窄转换发生。