Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can a std::tuple not be assigned with an initializer list?

Tags:

c++11

stdtuple

I wonder why this choice is made. It would allow to write many functions in a very clear and neat way.. for instance:

int greatestCommonDivisor(int a, int b)
{
    if (b > a)
        std::tie(a, b) = { b, a };
    while (b > 0)
        std::tie(a, b) = { b, a % b };
    return a;
}
like image 423
mr_T Avatar asked Nov 16 '16 11:11

mr_T


People also ask

How do you initialize STD tuple?

Initializing a std::tuple We can initialize a std::tuple by passing elements as arguments in constructor i.e. std::tuple<int, double, std::string> result1 { 22, 19.28, "text" }; // Creating and Initializing a tuple std::tuple<int, double, std::string> result1 { 22, 19.28, "text" };

What is std:: initializer list?

An object of type std::initializer_list<T> is a lightweight proxy object that provides access to an array of objects of type const T .

What is initializer list in c++?

Initializer List is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon. Following is an example that uses the initializer list to initialize x and y of Point class.


1 Answers

std::initializer_list is a homogeneous collection of items, while std::tuple is heterogeneous. The only case where it makes sense to define a std::tuple::operator= for std::initializer_list is when the tuple is homogeneous and has the same size as the initializer list, which is a rare occurrence.

(Additional information in this question.)


Solution/workaround: you can use std::make_tuple instead:

int greatestCommonDivisor(int a, int b)
{
    if (b > a)
        std::tie(a, b) = std::make_tuple(b, a);
    while (b > 0)
        std::tie(a, b) = std::make_tuple(b, a % b);
    return a;
}

...or std::tuple's constructor in C++17 (thanks to Template argument deduction for class templates):

int greatestCommonDivisor(int a, int b)
{
    if (b > a)
        std::tie(a, b) = std::tuple{b, a};
    while (b > 0)
        std::tie(a, b) = std::tuple{b, a % b};
    return a;
}
like image 151
Vittorio Romeo Avatar answered Oct 13 '22 17:10

Vittorio Romeo