Search code examples
c++templatestemplate-argument-deduction

Better way to disable template argument deduction from a specific function parameter?


Here is what I want to do:

template <typename T> void f(DisableDeduction<T> obj) {std::cout << obj;}
// Here DisableDeduction<T> aliases T, but in a such way
// that would prevent compiler from deducing T based
// on provided argument.

/* ... */

f<int>(1); // Works.
f(1); // Error, can't deduce template parameter based on argument.

This is how I currently achieve it:

template <typename T> struct DisableDeduction_Internal {using type = T;};
template <typename T> using DisableDeduction = typename DisableDeduction_Internal<T>::type;

It works perfectly (as described), but it introduces one extra helper type.

But can I achieve same result without extra types?


Solution

  • Since C++20 you can use std::type_identity_t<T>.

    Pre-C++20 I would suggest std::enable_if_t<true, T>.

    std::common_type_t<T>, while seemingly innocuous, applies std::decay to the type, removing const, volatile, and/or reference-ness.