4

I have a requirement where tuple needs to be initialized as follows. How do I create a tuple containing class A's object?

#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 can't modify the class A in any manner.

AAA
  • 348
  • 1
  • 4
  • 19
  • 1
    What are you _actually_ trying to do, and what are your _actual_ constraints? I mean, we can probably deduce/guess it from your code in this case, but you should use _words_ to explain it so that this question is searchable and re-usable and clear. – Lightness Races in Orbit May 07 '16 at 19:46
  • `std::forward` doesn't work the way you think it works. In your case you don't need `std::forward` anywhere. – bolov May 07 '16 at 19:57
  • also in `createTuple` you are trying to return an lvalue reference to a temporary object. I – bolov May 07 '16 at 19:58

1 Answers1

2

Like so:

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

A's move constructor isn't implicitly declared since you deleted the copy constructor (which should take an A const& btw), so the form you're trying to use wouldn't be valid outside of tuple anyway:

A a = A(1); // error

If you need a move constructor, you'll need to explicitly write one:

A(A&& rhs) = default;

at which point this would work:

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

Note that the forward is redundant since A(1) is already an rvalue.


I can't modify the class A in any manner.

Given that, you cannot make a std::tuple<A>. The member int is private, so you can't access it to use the int constructor like I initially proposed. There is no move constructor, so you can't use that one either. Those were your two options - neither of which are apparently viable.

Moreover, you cannot even make a std::tuple<std::shared_ptr<A>> since again A is noncopyable and you have no way to get at the int member.

Game over, man. Game over.

Barry
  • 286,269
  • 29
  • 621
  • 977