模板专业化仅用于基本POD [英] Template Specialization for basic POD only
问题描述
有一个微妙的技巧模板专门化,所以我可以应用一个专门化到基本POD
(当我说基本POD我不特别想要struct POD
Is there a subtle trick for template specialization so that I can apply one specialization to basic POD
(when I say basic POD I don't particularly want struct POD (but I will take that)).
template<typename T>
struct DoStuff
{
void operator()() { std::cout << "Generic\n";}
};
template<>
struct DoStuff</*SOme Magic*/>
{
void operator()() { std::cout << "POD Type\n";}
};
或者我必须为每个内置类型写专门化吗?
Or do I have to write specializations for each of the built in types?
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类型,那么以下应该工作:
If you really want only fundamental types and not user-defined POD types then the following should work:
#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并且这样做的优化目的, code> std :: is_trivially_copyable<> )。
If you also want user-defined POD types, then use boost::is_pod<>
instead of non_void_fundamental<>
(and if you're using C++11 and doing this for optimization purposes, use std::is_trivially_copyable<>
instead).
这篇关于模板专业化仅用于基本POD的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!