这可能有一个非常简单的答案,但我真的想不通。为什么我这样做会出错?初始化这样的东西的正确方法是什么?
std::array<std::tuple<int, std::string>, 3> tuples{
{3, "a"},
{7, "b"},
{2, "c"}
};
在 MSVC 2015 上,我收到以下错误:
No suitable constructor exists to convert from "int" to "std::tuple<int, std::string>"
No suitable constructor exists to convert from "const char[2]" to "std::tuple<int, std::string>"
最佳答案
这是 tuple
的一个突出问题。看,its constructor in C++11/14 is explicit
.因此,它不能参与复制列表初始化,这是内部大括号初始化列表所做的(外部是直接列表初始化)。
想法是 prevent you from being able to bypass a class's explicit
constructors through tuple
.但是,在 C++17 中,这将发生变化:如果元组的所有类型本身都可以从各自的给定类型隐式转换,那么 tuple
的构造函数也是如此。
对于您的特定用例,您可以使用 std::pair。它的构造函数从不显式
。
关于c++ - 用花括号初始化一个 std::array of tuples,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37188544/