Initializing std::tuple from initializer list

前端 未结 1 1640
梦毁少年i
梦毁少年i 2020-12-24 10:25

I\'m wondering whether the tuple can be initialized by initializer list (to be more precise - by initializer_list of initializer_lists)? Considering the tuple definition:

相关标签:
1条回答
  • 2020-12-24 11:00

    Initializer lists aren't relevant for tuples.

    I think that you're confusing two different uses of curly braces in C++0x.

    1. initializer_list<T> is a homogeneous collection (all members must be of the same type, so not relevant for std::tuple)
    2. Uniform initialization is where curly brackets are used in order to construct all kinds of objects; arrays, PODs and classes with constructors. Which also has the benefit of solving the most vexing parse)

    Here's a simplified version:

    std::tuple<int, char> t = { 1, '1' }; 
    // error: converting to 'std::tuple<int, char>' from initializer list would use
    // explicit constructor 'std::tuple<_T1, _T2>::tuple(_U1&&, _U2&&) 
    // [with _U1 = int, _U2 = char, _T1 = int, _T2 = char]'
    
    std::tuple<int, char> t { 1, '1' }; // note no assignment
    // OK, but not an initializer list, uniform initialization
    

    The error message says is that you're trying to implicitly call the constructor but it's an explicit constructor so you can't.

    Basically what you're trying to do is something like this:

    struct A { 
        explicit A(int) {}
    };
    
    A a0 = 3;
    // Error: conversion from 'int' to non-scalar type 'A' requested
    
    A a1 = {3}; 
    // Error: converting to 'const A' from initializer list would use 
    // explicit constructor 'A::A(int)'
    
    A a2(3); // OK C++98 style
    A a3{3}; // OK C++0x Uniform initialization
    
    0 讨论(0)
提交回复
热议问题