'Better way to disable argument-based template parameter deduction for functions?
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 1:[1]
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.
Solution 2:[2]
You can do it by putting T in non deducible 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;}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | HolyBlackCat |
| Solution 2 | marcinj |
