Best way to turn off the output of template parameters based on arguments?

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. 

Here is how I am currently achieving this:

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

It works fine (as described), but it introduces one additional helper type.

But can I achieve the same result without additional types?

+8
c ++ templates
source share
1 answer

You can do this by putting T in a non-output context (to the left of ::) and use std :: common_type from <type_traits> .

Example:

 template <typename T> void f(typename std::common_type<T>::type obj) {std::cout << obj;} 
+7
source share

All Articles