user2770808
user2770808

Reputation: 347

How to pass real type of auto into template

So I have something for example

auto a = getMyTuple();

which will eventually be real type of std::tuple<(some args)>

Now I want to store this in a class which has a template since I dont know the type yet. Something along the lines of

template<typename T>
class my_tuple
{
  public:
  T mt;

  my_tuple(T t)
  {
    mt = t;
  }
};

My question is, is there a way to get the type returned by auto, so I can pass it into the template class like

my_tuple<getType(a)> myTup(a);

Upvotes: 4

Views: 107

Answers (3)

Drop
Drop

Reputation: 13003

You could implement a factory function that will construct your objects, the same way as std::make_tuple() constructs std::tuple.

(simplified version, see more plausible version in the link above or in your favorite standard library's source code)

template <typename T>
my_tuple<T> my_make_tuple(T t) {
    return my_tuple<T>(t);
}

auto myTup = my_make_tuple(a);

Function call template argument deduction will figure out the types automagically, so you don't need to worry about explicit types anymore. This is how they do it in standard library.

See this talk by Stephan T. Lavavej: Don’t Help the Compiler (towards the second half of it)

Update: I think that the solutions with decltype posted around are ugly and error prone, because of the repetition of the variable name (violation of DRY principle). Also, decltype is unnecessary here as types can be deduced automatically with the use of a function wrapper. Finally, if your tuple would have 25 parameters will you write decltype 25 times? What if you accidentally mix the order of types and the order of parameters?

Upvotes: 0

songyuanyao
songyuanyao

Reputation: 172924

You want decltype (since C++11):

my_tuple<decltype(a)> myTup(a);

Upvotes: 3

Sam Varshavchik
Sam Varshavchik

Reputation: 118340

That's what decltype is for:

my_tuple<decltype(a)> myTup(a);

Upvotes: 9

Related Questions