Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

c++ - Initialize an std::array of tuples with curly braces

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"}
};

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>"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...