Mar*_*ork 6 c++ templates pod template-specialization
是否有一个模板专业化的微妙技巧,以便我可以应用一个专业化basic 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";}
};
Run Code Online (Sandbox Code Playgroud)
或者我是否必须为每个内置类型编写特化?
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";}
};
Run Code Online (Sandbox Code Playgroud)
单元测试.
int main()
{
DoStuff<int> intStuff;
intStuff(); // Print POD Type
DoStuff<std::string> strStuff;
strStuff(); // Print Generic
}
Run Code Online (Sandbox Code Playgroud)
如果您真的只想要基本类型而不是用户定义的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
};
Run Code Online (Sandbox Code Playgroud)
如果您还想要用户定义的POD类型,那么请使用boost::is_pod<>而不是non_void_fundamental<>(如果您使用的是C++ 11并且为了优化目的而这样做,请std::is_trivially_copyable<>改用).
在C++ 11中,许多特征已被添加到标准库中,并且大多数特征似乎特别针对有趣的特化(尤其是按位操作).
您可能感兴趣的顶级特征是std::is_trivial,但还有许多其他特征:
std::is_trivially_default_constructiblestd::is_trivially_copy_constructiblestd::is_trivially_move_constructiblestd::is_trivially_copyable(可以复制memcpy)一般来说,标准一直试图所以你不必依靠如此广泛的假设,得到的更细粒度的特质尽可能is_pod而是微调约束,以配合你的方法真正需要的.