问题描述
考虑类模板,可以使用类型traits和dummy启用程序模板参数为某些类型的组提供模板特化。我已经。
现在,对于函数模板,我需要相同的东西:我有一个模板函数,想要一组类型的特殊化,例如,所有类型是一个类的子类型 X
。我可以用类型traits来表达这样的:
std :: enable_if< std :: is_base_of< X,T& value> :: type
我想到这样做:
模板< typename T,typename ENABLE = void>
void foo(){
//做某事
}
template< typename T>
void foo< T,std :: enable_if< std :: is_base_of< A,T> :: value> :: type>(){
// Do something different
}
但是,这不起作用,因为函数模板不允许部分专门化。那么如何做呢?也许缺省参数类型trait作为类型?但是代码怎么样呢?
最接近你要求的是 enable_if
在返回类型上:
template< typename T& typename std :: enable_if< std :: is_same< T,int> :: value> :: type foo()
template< typename T> typename std :: enable_if< std :: is_same< T,char> :: value> :: type foo()但是,调度到辅助函数或类可能会更加可读和高效。 >
辅助功能:
模板< typename T> void foo_helper(std :: true_type);
template< typename T> void foo_helper(std :: false_type);
template< typename T> void foo(){foo_helper(std :: is_same< T,int>()); }
助手类:
template< typename T,bool = std :: is_same< T,int> :: value> struct foo_helper {};
template< typename T> struct foo_helper< T,true> {static void foo(); };
template< typename T> struct foo_helper< T,false> {static void foo(); };
template< typename T> void foo(){foo_helper< T> :: foo(); }
Considering class templates, it is possible to provide template specializations for certain types of groups using type traits and dummy enabler template parameters. I've already asked that earlier.
Now, I need the same thing for function templates: I.e., I have a template function and want a specialization for a group of types, for example, all types that are a subtype of a class X
. I can express this with type traits like this:
std::enable_if<std::is_base_of<X, T>::value>::type
I thought about doing it this way:
template <typename T, typename ENABLE = void>
void foo(){
//Do something
}
template <typename T>
void foo<T,std::enable_if<std::is_base_of<A, T>::value>::type>(){
//Do something different
}
However, this does not work since partial specialization is not allowed for function templates. So how to do it then? Maybe a default parameter with the type trait as type? But how does the code look like then?
解决方案 The closest to what you're asking is enable_if
on the return type:
template<typename T> typename std::enable_if<std::is_same<T, int>::value>::type foo();
template<typename T> typename std::enable_if<std::is_same<T, char>::value>::type foo();
However, dispatching to a helper function or class is likely to be more readable and efficient.
Helper function:
template<typename T> void foo_helper(std::true_type);
template<typename T> void foo_helper(std::false_type);
template<typename T> void foo() { foo_helper(std::is_same<T, int>()); }
Helper class:
template<typename T, bool = std::is_same<T, int>::value> struct foo_helper {};
template<typename T> struct foo_helper<T, true> { static void foo(); };
template<typename T> struct foo_helper<T, false> { static void foo(); };
template<typename T> void foo() { foo_helper<T>::foo(); }
这篇关于功能模板:具有类型traits的不同专业化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!