【发布时间】:2012-01-14 17:30:55
【问题描述】:
模板专业化是否有一个微妙的技巧,以便我可以将一个专业化应用于basic POD(当我说基本 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 类型的实现并没有什么不同,该怎么办?
-
我正在使用 boost::mpl。对于类对象,我需要注册一个操作类对象的操作(并为其所有成员注册操作)。对于普通的 POD 对象,我有一个更简单的操作,它将被注册以对对象执行操作。
标签: c++ templates template-specialization