是否有可能在没有编译失败的情况下推断类型是否不完整

Is it possible to deduce whether type is incomplete without compilation failure?

本文关键字:是否 下推 类型 情况下 有可能 失败 编译 情况      更新时间:2023-10-16

我想实现这样的行为sizeof(complete_type)将返回真正的sizeof, sizeof(incomplete_type) -将只是0

我需要它为IPC(进程间)通信提供扩展的运行时类型信息,每个类型的描述结构:

struct my_type_info
{
    bool   is_pointer;
    size_t size;         //for double* will be 4 on i386. that is sizeof(double*)
    size_t base_size;    //for double* will be 8. that is sizeof(double)
};

问题出现时,进入我的系统像类MyOnlyDeclaredClass;我得到了编译错误,显然是因为我不能取它的大小。

boost type_traits http://www.boost.org/doc/libs/1_48_0/libs/type_traits/doc/html/index.html建议使用许多编译时类,但是没有'is_incomplete'

有趣的编译器有VS2008, VS2010, clang 3, gcc-4.6, gcc-4.7

不要这么做。

这根本是不合理的。模板是通过类型参数化的,而不是实例化点。类类型不完整或本身不完整,它在翻译过程中的某个时刻是完整的。

在某些类型上实例化的模板在每次实例化时必须具有完全相同的语义。

像往常一样使用SFINAE。这是一种可能的实现:

struct char256 { char x[256]; };
template <typename T>
char256 is_complete_helper(int(*)[sizeof(T)]);
template <typename>
char is_complete_helper(...);
template <typename T>
struct is_complete
{
    enum { value = sizeof(is_complete_helper<T>(0)) != 1 };
};

的例子:

#include <cstdio>
struct F;
struct G {};
int main()
{
    printf("%d %dn", is_complete<F>::value, is_complete<G>::value);
    return 0;
}

(注意:适用于gcc 4.5(不,不是因为c++ 0x)和clang 2.9,但不适用于gcc 4.3)

相关文章: