c++ - 仅用于基本 POD 的模板特化

标签 c++ templates template-specialization

模板特化是否有一个微妙的技巧,以便我可以将一种特化应用于 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/

相关文章:

c++ - 无法弄清楚如何在 CRTP 模板类上正确地专门化 fmt 模板

c++ - 如何使用模板创建带有斐波那契数的编译时模板化集/数组/vector ?

c++ - 尝试制作一个 while 循环,减去一个数字直到达到所需值,如果减法超过所需值,则显示并停止

javascript - 将 URL 从 javascript 传递到 ActiveX 会是一个安全漏洞吗?

c++ - 运行时错误问题

C++重载优先于特化?

C++无限循环

c++ - 虚拟成员函数的打印地址

c++ - 在 C++ 中将内部模板类作为模板参数传递

c++ - 如何对通过几层模板派生的类型进行typedef?