我目前有一个功能:
template<typename T>
bool func(T &t, int x)
{
// do stuff...
}
但是我想要三个不同的函数体:
-
T
是一个enum
-
T
being unsigned char
- 其他一切
我努力了this已经但没有走远。
对于这三种情况,正确的函数声明是什么?
我能想到的最接近的是案例 1:
template<typename T>
typename std::enable_if< std::is_enum<T>::value, bool >::type func( T &t, int x)
案例 3 是:
template<typename T>
typename std::enable_if< not std::is_enum<T>::value, bool >::type func( T &t, int x)
但是我无法为案例 2 进行编译。作为解决方法,我有一个if
Case 3 中的语句来处理无符号字符,但这并不理想。
使用标签调度:
namespace details {
template<class T>
bool func( T& t, int x, std::true_type /* is_enum */, std::false_type ) {
}
template<class T>
bool func( T& t, int x, std::false_type, std::true_type /* unsigned char */ ) {
}
template<class T>
bool func( T& t, int x, std::false_type, std::false_type ) {
// neither
}
}
template<class T>
bool func( T& t, int x ) {
return details::func( t, x, std::is_enum<T>{}, std::is_same<unsigned char, T>{} );
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)