如何确定模板专业化是否存在 [英] How to decide if a template specialization exist

查看:45
本文介绍了如何确定模板专业化是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查是否存在某种模板专业化,而一般情况未定义。

I would like to check if a certain template specialization exist or not, where the general case is not defined.

给出:

template <typename T> struct A; // general definition not defined
template <> struct A<int> {};   // specialization defined for int

定义的专业化

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

I would like to define a struct like this:

template <typename T>
struct IsDefined
{
    static const bool value = ???; // true if A<T> exist, false if it does not
};

有没有办法做到这一点(最好没有C ++ 11)?

Is there a way to do that (ideally without C++11)?

谢谢

推荐答案

使用无法应用的事实 sizeof 到不完整的类型:

Using the fact that you can't apply sizeof to an incomplete type:

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*>()));

在Coliru上直播

这里有点笨重,但可以运行C ++ 03解决方案:

Here is a slightly clunky, but working C++03 solution:

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

在Coliru上实时观看

这篇关于如何确定模板专业化是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆