20

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>"
YSC
  • 38,212
  • 9
  • 96
  • 149
Alex
  • 3,111
  • 6
  • 27
  • 43

1 Answers1

25

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.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • 1
    So that's why the other guy's deleted answer actually worked before I posted. I thought that might've been doing something else I wasn't expecting. Guess I'll have to use a C array or just do it that way then. Ugh... C++17 can't come fast enough – Alex Jan 10 '16 at 18:06
  • 1
    @AlexYan: You could use `pair`, since your current type only has two memebers. – Nicol Bolas Jan 10 '16 at 18:08
  • "_The idea was to prevent you from being able to bypass a class's explicit constructors through tuple_" Do you have a reference of where that was discussed? – edmz Jan 10 '16 at 18:17
  • Do you know what feature this is called? Just curious if there's any support for it on any of the current compilers – Alex Jan 10 '16 at 18:40
  • @AlexYan: I doubt this has a formal name. But [the most recent paper discussing it is N4387](http://wg21.link/N4387). – Nicol Bolas Jan 10 '16 at 18:42
  • @black: Reference added. – Nicol Bolas Jan 10 '16 at 18:46
  • More excited for C++17 or Star Wars VIII? – Charles Jan 10 '16 at 23:35