c++ - 用花括号初始化一个 std::array of tuples

标签 c++ c++11

这可能有一个非常简单的答案,但我真的想不通。为什么我这样做会出错?初始化这样的东西的正确方法是什么?

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/

相关文章:

c++ - 使用条件变量的生产者和消费者线程

c++ - 是否可以打印宽度为5的 vector 内容?

c++ - 静态成员变量的返回引用c++

c++ - loop-malloc.c : No such file or directory vector 中的段错误

c++ - 我无法在代码中找到最大的素数错误?

c++ - 如何在 C++ 中打印 system() 输出?

c++ - 为什么返回类型在函数名之前?

c++ - 在这种情况下如何正确使用 std::enable_if

c++ - 从森林中构建一棵 n 叉树

c++ - C++ 在多大程度上是一种静态类型语言?