TestUser
TestUser

Reputation: 967

Can I stop c++ template argument from being deduced?

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?

Upvotes: 1

Views: 291

Answers (2)

LWimsey
LWimsey

Reputation: 6707

You can use std::type_identity (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; ie. it does not accept an lvalue argument, unless you instantiate with an lvalue reference type.

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

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

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

foo<int&>(i); // ok
foo<int>(42); // ok

Upvotes: 3

sp2danny
sp2danny

Reputation: 7687

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

Upvotes: 2

Related Questions