如何专门化一个模板函数的枚举,和具体类型? [英] How to specialize a template function for enum, and specific type?
本文介绍了如何专门化一个模板函数的枚举,和具体类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前有一个函数:
template< typename T&
$然而,我想有三个不同的函数体:
bool func(T& t,int x)
{
// do stuff ...
}
- <$> c $ c> T 是
枚举
T
unsigned char
- 其他一切
我已尝试过 this ,但didn
这三种情况下正确的函数声明是什么?
我能够想出的最接近的是案例1:
template<类型名T>
typename std :: enable_if< std :: is_enum< T> :: value,bool> :: type func(T& t,int x)
b $ b并且情况3是:
template< typename T>
typename std :: enable_if< not std :: is_enum< T> :: value,bool> :: type func(T& t,int x)
但是我无法为编译的案例2做一些工作。作为解决方法我在案例3中有一个
if
语句来处理unsigned chars,但这不是理想的。解决方案使用标签分派:
命名空间详细信息{
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){
//没有
}
}
模板< class T> ;
bool func(T& t,int x){
return details :: func(t,x,std :: is_enum< T> {},std :: is_same< unsigned char,T& });
}
I currently have a function:
template<typename T> bool func(T &t, int x) { // do stuff... }
However I would like to have three different function bodies:
T
being anenum
T
beingunsigned char
- Everything else
I have tried this already but didn't get far.
What are the correct function declarations for these three cases to work?
The closest I have been able to come up with is Case 1 being:
template<typename T> typename std::enable_if< std::is_enum<T>::value, bool >::type func( T &t, int x)
and Case 3 being:
template<typename T> typename std::enable_if< not std::is_enum<T>::value, bool >::type func( T &t, int x)
however I have not been able to make something work for Case 2 that compiles. As a workaround I have an
if
statement inside Case 3 to handle unsigned chars but that is not ideal.解决方案Use tag dispatching:
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>{} ); }
这篇关于如何专门化一个模板函数的枚举,和具体类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文