模板特化是否有一个微妙的技巧,以便我可以将一种特化应用于 basic POD
(当我说 basic POD 时,我并不是特别想要 struct 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<>
)。
关于c++ - 仅用于基本 POD 的模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8863965/