Wil*_*mKF 7 c++ templates traits template-specialization
在C++中,如果我有模板参数,我如何干净地专门化默认参数?例如,请考虑以下事项:
template <class Key, class Value = int > class Association;
Run Code Online (Sandbox Code Playgroud)
如果我想Value默认float为课程Special怎么办?有没有办法实际上专门化类Association,如果键是Special值默认值而不是float?
我想有一种方法可以做到这一点:
template <class Key> struct Traits {
typedef int defaultValue;
}
template<> struct Traits<Special> {
typedef float defaultValue;
}
template <class Key, class Value = Traits<Key>::defaultValue> class Association;
Run Code Online (Sandbox Code Playgroud)
是否有一种更简洁的方式来做到这一点并没有那么复杂,并且更容易证明int是定义Association的地方的正常默认值?
嗯,一个不一定更漂亮的单线:
#include <type_traits>
template <typename Key,
typename Value = typename std::conditional<std::is_same<Key, Special>::value, float, int>::type>
class Association { /* ... */ };
Run Code Online (Sandbox Code Playgroud)