This question already has answers here:
Identifying primitive types in templates

(8个答案)


3年前关闭。




在专门化类模板时,我希望有一个专门化目标全面的类(具有构造函数,析构函数等),以及一个专门化目标基本体(intfloat等)。我见过的唯一的部分特化对象是定位指针类型(通过T*)。有没有办法做到这一点?

最佳答案

您可以使用C++ 11 type_traits。以下是一些入门知识,您可以根据需要进行更多特化:

#include <type_traits>
#include <iostream>

template<typename T, typename E = void>
struct A; // undefined

template<typename T>
struct A<T, typename std::enable_if<std::is_class<T>::value && !std::is_pod<T>::value>::type> {
        A() { std::cout << "I'm a class, but I'm not a pod type" << std::endl; }
};

template<typename T>
struct A<T, typename std::enable_if<std::is_class<T>::value && std::is_pod<T>::value>::type> {
        A() { std::cout << "I'm a class and a pod type" << std::endl; }
};

template<typename T>
struct A<T, typename std::enable_if<!std::is_class<T>::value>::type> {
        A() { std::cout << "I'm not a class" << std::endl; }
};

class X {};
class Y { ~Y(){} };

int main()
{
        A<X> a1;
        A<Y> a2;
        A<int> a3;
}

10-08 07:33
查看更多