使用SFINAE检查类型是否完整 [英] Using SFINAE to check if the type is complete or not

查看:83
本文介绍了使用SFINAE检查类型是否完整的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用SFINAE检查类型是否已完全定义?

Is it possible to check with SFINAE if the type is completely defined?

例如

template <class T> struct hash;
template <>        struct hash<int> {};

// is_defined_hash_type definition...

enum Enum { A, B, C, D };

static_assert (  is_defined_hash_type<int> ::value, "hash<int> should be defined");
static_assert (! is_defined_hash_type<Enum>::value, "hash<Enum> should not be defined");

该解决方案不应修改哈希结构.

推荐答案

您可以使用is_complete类型的特征,因为它的格式不正确,无法评估sizeof(T)的不完全类型T:

You can make an is_complete type trait, using the fact that it is ill-formed to evaluate sizeof(T) for an incomplete type T:

template <typename T>
struct is_complete_helper {
    template <typename U>
    static auto test(U*)  -> std::integral_constant<bool, sizeof(U) == sizeof(U)>;
    static auto test(...) -> std::false_type;
    using type = decltype(test((T*)0));
};

template <typename T>
struct is_complete : is_complete_helper<T>::type {};

,并通过确定hash<T>是否完成使用它来检查is_defined_hash_type<T>. (在Coliru直播)

and use it to check for is_defined_hash_type<T> by determining if hash<T> is complete. (Live at Coliru)

正如丹尼尔(Daniel)在回答中所说,这种事情的效用是有限的.特质实际上并不测试您查询的代码中该类型是否完整,它会在程序中首次针对给定类型实例化该特质的位置上测试该类型是否完整.

As Daniel says in his answer, the utility of such a thing is limited. The trait doesn't actually test if the type is complete at the point in the code where you query, it tests if the type was complete at the point in the program where the trait was first instantiated for a given type.

这篇关于使用SFINAE检查类型是否完整的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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