如何确定是否存在模板专门化

Fab*_*bio 15 c++ templates sfinae template-specialization

我想检查某个模板专业化是否存在,其中一般情况没有定义.

鉴于:

template <typename T> struct A; // general definition not defined
template <> struct A<int> {};   // specialization defined for int
Run Code Online (Sandbox Code Playgroud)

我想定义一个像这样的结构:

template <typename T>
struct IsDefined
{
    static const bool value = ???; // true if A<T> exist, false if it does not
};
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点(理想情况下没有C++ 11)?

谢谢

Que*_*tin 18

使用不能应用于sizeof不完整类型的事实:

template <class T, std::size_t = sizeof(T)>
std::true_type is_complete_impl(T *);

std::false_type is_complete_impl(...);

template <class T>
using is_complete = decltype(is_complete_impl(std::declval<T*>()));
Run Code Online (Sandbox Code Playgroud)

在Coliru上看到它


这是一个稍微笨重,但正在运行的C++ 03解决方案:

template <class T>
char is_complete_impl(char (*)[sizeof(T)]);

template <class>
char (&is_complete_impl(...))[2];

template <class T>
struct is_complete {
    enum { value = sizeof(is_complete_impl<T>(0)) == sizeof(char) };
};
Run Code Online (Sandbox Code Playgroud)

在Coliru上看到它