Home > Back-end >  Can I stop c template argument from being deduced?
Can I stop c template argument from being deduced?

Time:01-14

It's known that Template argument deduction takes place when you do not explicitly state the template argument, as in

template <typename T> void foo(T&& t) {};
 

Now we can invoke either as

foo(1);

foo('c')

Or

foo<int>(1);

foo<char>('c')

In first set of invocations template argument deduction will happen. But will there be no template argument deduction in second case where template argument is explicitly specified?

CodePudding user response:

Yes you can. Here is one way:

template<typename T>
struct nodeduce {
    typedef T type;
};

Then you use typename nodeduce<T>::type instead of T in the parameter list

CodePudding user response:

You can use std::type_identify (which was added in C 20)

void foo(std::type_identity_t<T> && t) {}

But note that this changes the function signature since the argument is no longer a forwarding reference and it no longer accept lvalue arguments, unless you instantiate with an lvalue reference.

foo(1); // error. requires explicit instantiation

foo('c')  // error, requires explicit instantiation

int i;
foo<int>(i); // error, requires rvalue

foo<int&>(i); //fine
foo<int>(42); // fine
  •  Tags:  
  • Related