模板专业化是否有一个微妙的技巧,以便我可以将一个专门化应用于基本POD(当我说基本POD我不特别想要结构POD(但我会采取那个)).
template<typename T> struct DoStuff { void operator()() { std::cout << "Generic\n";} }; template<> struct DoStuff</*SOme Magic*/> { void operator()() { std::cout << "POD Type\n";} };
或者我是否必须为每个内置类型编写特化?
template<typename T> struct DoStuff { void operator()() { std::cout << "Generic\n";} }; // Repeat the following template for each of // unsigned long long,unsigned long,unsigned int,unsigned short,unsigned char // long long,long,int,short,signed char // long double,double,float,bool // Did I forget anything? // // Is char covered by unsigned/signed char or do I need a specialization for that? template<> struct DoStuff<int> { void operator()() { std::cout << "POD Type\n";} };
单元测试.
int main() { DoStuff<int> intStuff; intStuff(); // Print POD Type DoStuff<std::string> strStuff; strStuff(); // Print Generic }
解决方法
如果您真的只想要基本类型而不是用户定义的POD类型,那么以下内容应该有效:
#include <iostream> #include <boost/type_traits/integral_constant.hpp> #include <boost/type_traits/is_fundamental.hpp> #include <boost/type_traits/is_same.hpp> template<typename T> struct non_void_fundamental : boost::integral_constant< bool,boost::is_fundamental<T>::value && !boost::is_same<T,void>::value > { }; template<typename T,bool Enable = non_void_fundamental<T>::value> struct DoStuff { void operator ()() { std::cout << "Generic\n"; } const }; template<> struct DoStuff<T,true> { void operator ()() { std::cout << "POD Type\n"; } const };
如果您还想要用户定义的POD类型,那么请使用boost :: is_pod<>而不是non_void_fundamental<> (如果您使用的是C 11并且为了优化目的,请使用std :: is_trivially_copyable<>).