How to initialize a tuple with a given class that does not have a copy constructor

I have a requirement when a tuple needs to be initialized as follows. How to create a tuple containing an object of class A?

#include <iostream>
#include <tuple>

using namespace std;

class A{
  int a;

public:
  A(const A&)=delete;
  A(int a): a(a){}
};

std::tuple<A>& createTuple(A &&a){
  return std::make_tuple<A>(std::forward<A>(a));
}
int main(){
  std::cout << std::get<0>(createTuple(std::forward<A>(A(1))));
}

I cannot modify class A in any way.

+4
source share
1 answer

Same:

std::tuple<A> t(1);

Athe move constructor is not implicitly declared, since you are the deleted copy constructor (which should accept A const&btw), so the form you are trying to use is not valid outside tupleanyway:

A a = A(1); // error

If you need a move constructor, you need to explicitly write it:

A(A&& rhs) = default;

at what point will this work:

std::tuple<A> t(A(1));

, forward , A(1) rvalue.


A .

, std::tuple<A>. int , , int, . , . - , -, .

, std::tuple<std::shared_ptr<A>>, A , int.

, . .

+1

All Articles