问题
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