Aman Deep Gautam
Aman Deep Gautam

Reputation: 8747

deduce type of variable dependent on template function type

I have a template function:

// Overloaded functions, Class1In, Class1Out, Class2In and Class2Out
// are defined in the code.  
Class1Out Init(Class1In one) { ... }
Class2Out Init(Class2In two) { ... }

template <class A>
void f(A a, int retry_count) {
  B b = Init(a); // How to express B?
}

Question is how can I express B? I tried the following, but it errors out saying that compiler cannot deduce B when I call f

template <class A, class B>
void f(A a, int retry_count) {
  B b = Init(a); // compiler error: Cannot deduce template parameter B
}

I cannot really call Init outside of f because the function retries by calling itself and needs to create a new instance of b every time it is called.

How would I achieve this?

Upvotes: 4

Views: 134

Answers (1)

You could use auto, but in general you can use this trick to determine the type B:

using outType = decltype(Init(std::declval<A&>()));

for your particular case you can also use the simpler format (thanks user max66):

using outType = decltype(Init(a));

This allows you to know the type of b without needing to instantiate it.

If you need to instantiate b then you can also try

auto b = Init(a);
using outType = decltype(b);

In the below code I show the use adding some boilerplate code.

#include <type_traits>

class Class1Out{};
class Class2Out{};

class Class1In{};
class Class2In{};


Class1Out Init(Class1In one);
Class2Out Init(Class2In two);

template <class A>
void f(A a, int retry_count) {

  using outType = decltype(Init(std::declval<A&>()));
  outType b = Init(a); // How to express B?
}


int main(){

    Class1In in1{};
    Class2In in2{};

    f(in1, 4);
    f(in2, 4);
}

For more info about std::declval and decltype please see: https://en.cppreference.com/w/cpp/utility/declval and https://en.cppreference.com/w/cpp/language/decltype

Upvotes: 6

Related Questions