Is there a way to specialize a template to target primitives? [duplicate]

我的梦境 提交于 2019-12-19 09:57:53

问题


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?


回答1:


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



回答2:


boost::has_trivial_assign should give you this info.

template <class T>
  struct has_trivial_assign : public true_type-or-false_type {};

http://www.boost.org/doc/libs/1_50_0/libs/type_traits/doc/html/boost_typetraits/reference/has_trivial_assign.html



来源:https://stackoverflow.com/questions/11287043/is-there-a-way-to-specialize-a-template-to-target-primitives

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!