Better way to disable argument-based template para

2020-07-06 04:11发布

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?

标签: c++ templates
1条回答
别忘想泡老子
2楼-- · 2020-07-06 04:28

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;}
查看更多
登录 后发表回答