是否可以推断类型是否是不完整的,无编译失败? [英] Is it possible to deduce whether type is incomplete without compilation failure?
问题描述
我想实现行为像sizeof(complete_type)将返回实际sizeof和sizeof(incomplete_type) - 将只是0
I want to achieve behavior like sizeof(complete_type) will return real sizeof, and sizeof(incomplete_type) - will be just 0
我需要这个提供扩展运行用于具有每种类型描述结构的IPC(进程间)通信的时间类型信息:
I need this to provide extended run time type information for IPC(inter-process) communication with the description structure per type:
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;我收到编译错误,显然是因为我不能把它的大小。
The problem appears when into my system goes something like class MyOnlyDeclaredClass; I got compilation error, obviously by reason I can't take size of it.
boost type_traits http://www.boost.org/doc/libs/1_48_0/libs/type_traits/doc/html/index.html 建议许多编译时类,但没有is_incomplete
boost type_traits http://www.boost.org/doc/libs/1_48_0/libs/type_traits/doc/html/index.html suggests many compile-time classes, but there is no 'is_incomplete'
有趣的编译器是VS2008,VS2010,clang 3,gcc-4.6,gcc-4.7
Interesting compilers are VS2008, VS2010, clang 3, gcc-4.6, gcc-4.7
推荐答案
使用 SFINAE ,一如往常。这是一个可能的实现:
Use SFINAE, as usual. This is one possible implementation:
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 %d\n", is_complete<F>::value, is_complete<G>::value);
return 0;
}
(注意: gcc 4.5 (不是因为C ++ 0x)和ang 2.9,但不是gcc 4.3 )
(Note: Works on gcc 4.5 (no it's not because of C++0x) and clang 2.9, but not gcc 4.3)
这篇关于是否可以推断类型是否是不完整的,无编译失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!