Search code examples
c++templatesprimitive

Is there a way to specialize a template to target primitives?


In specializing a class template, I would like to have one specialization target full-blown classes (complete with constructor, destructor, etc.) and one specialization target primitives (int, float, etc.). The only partial specialization I've seen is with targeting pointer types (via T*). Is there a way to do this?


Solution

  • You can used C++11 type_traits. Here is something to get you started, you can specialize more as needed:

    #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;
    }