Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize std::tuple with classes which have two or more arguments [duplicate]

#include <iostream>

class NoCopyMove {
public:
    NoCopyMove(int a) : a_(a), b_(a) {}
    NoCopyMove(int a, int b) : a_(a), b_(b) {}

    NoCopyMove(const NoCopyMove&) = delete;
    NoCopyMove& operator=(const NoCopyMove&) = delete;
    NoCopyMove(NoCopyMove&&) = delete;
    NoCopyMove& operator=(NoCopyMove&&) = delete;

    int a_;
    int b_;
};

int main()
{
    std::tuple<NoCopyMove, NoCopyMove> t {6, 9};
    std::cout << std::get<0>(t).a_ << std::endl;   
    std::tuple<NoCopyMove, NoCopyMove> t2 {{6, 7}, {8, 9}};
    return 0;
}

I'm trying to make a tuple of classes that has more than 2 arguments as their constructor. If there is just one constructor argument it works.

main.cpp:45:28: error: no matching constructor for initialization of 'std::tuple<NoCopyMove>'
    std::tuple<NoCopyMove> t2 {{6, 7}, {8, 9}}};
                           ^  ~~~~~~~~~~~~~~~~

Probably some kind of hint to the compiler would be needed but I have no idea how I could do that. Any kind of keyword and hint will be appreciated.

like image 618
Daniel Lee Avatar asked Feb 22 '26 07:02

Daniel Lee


1 Answers

Aside from the extraneous closing brace, there is no way you can construct a tuple of uncopyable and immoveable types like this. std::tuple does not support piecewise or 'emplace-style' construction and as mentioned in the comments it is also not an aggregate, so it needs to copy or move the individual elements in place. The constructor you would expect to be chosen here is the one which takes each type in the tuple by const & and quoting cppreference:

This overload participates in overload resolution only if sizeof...(Types) >= 1 and std::is_copy_constructible::value is true for all i.

However your types are not copy constructible, so you are out of luck if this really is what you need to do.

like image 90
chrysante Avatar answered Feb 23 '26 21:02

chrysante



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!