如何在嵌套列表初始化中从map<><>中辨别向量?

How to discern vector<> from map<> in nested list initialization?

本文关键字:lt gt 向量 map 嵌套 列表 初始化      更新时间:2023-10-16

考虑一个定义为:

class C {
    public:
    C(std::vector<std::string>) {};           // (1)
    C(std::map<std::string, std::string>) {}; // (2)
};

然后是它的两个实例,使用列表初始值设定项创建,如下所示:

C A({ "A", "B" });
C B({ { "A", "B" }, { "C", "D" } });

我希望对象A使用(1)构造函数和对象B经历(2)。但事实并非如此,我得到以下输出:error: call to constructor of 'C' is ambiguous.

此外,如果我尝试声明这些实例,例如:

C A = { "A", "B" };
C B = { { "A", "B" }, { "C", "D" } };

它失败了:error: no matching constructor for initialization of 'C' .

这是怎么回事?

我怎样才能达到预期的行为?( A -> (1)B -> (2) (也许以某种方式使用SFINAE?

我通过以下方式实现了您想要的:

class C {
    public:
    C(std::vector<std::string>) { std::cout << "here1" << std::endl; }           // (1)
    C(std::map<std::string, std::string>) { std::cout << "here2" << std::endl; } // (2)
};
int main()
{
    C A = C( { {"A"}, {"B"} });
    C B = C( std::map<std::string, std::string> { {"A", "B"}, {"C", "D"} } );
    // or C B = C( { std::make_pair("A", "B"), std::make_pair("C", "D") } );
}

已编辑(使用统一初始化(