使用花括号来初始化元组的std ::数组 [英] Initialize an std::array of tuples with curly braces

查看:345
本文介绍了使用花括号来初始化元组的std ::数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能有一个非常简单的答案,但我真的不能弄清楚。为什么我会收到错误这样做?

This probably has a very simple answer, but I really can't figure it out. Why do I get errors for doing this? What's the correct way to initialize something like this?

std::array<std::tuple<int, std::string>, 3> tuples{
    {3, "a"},
    {7, "b"},
    {2, "c"}
};






在MSVC 2015上,我遇到以下错误:


On MSVC 2015, I get the following errors:

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 。请参阅其在C ++ 11/14中的构造函数 explicit 。因此,它不能参与拷贝列表初始化,这是内部支撑初始化列表做的(外部的是直接列表初始化)。

This is an outstanding issue with tuple. See, its constructor in C++11/14 is explicit. And therefore, it cannot participate in copy-list-initialization, which is what the inner braced-init-lists do (the outer ones are direct-list-initialization).

这个想法是阻止你绕过类的显式构造函数通过 tuple 。但是,在C ++ 17中,这将改变:如果所有的元组类型本身都是可以从相应的给定类型隐式转换的,那么 tuple

The idea was to prevent you from being able to bypass a class's explicit constructors through tuple. But, in C++17, this will be changed: if all of the tuple's types themselves are implicitly convertible from the respective given type, then so too will that constructor of tuple.

对于特定的用例,可以使用std :: pair。它的构造函数从不显式

For your specific use case, you could use std::pair. Its constructor is never explicit.

这篇关于使用花括号来初始化元组的std ::数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆