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

…衆ロ難τιáo~ 提交于 2019-12-01 20:12:36

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

Example:

#include <cstdio>

struct F;
struct G {};

int main()
{
    printf("%d %d\n", is_complete<F>::value, is_complete<G>::value);
    return 0;
}

(Note: Works on gcc 4.5 (no it's not because of C++0x) and clang 2.9, but not gcc 4.3)

Do not try to do that.

It is fundamentally unsound. Templates are parametrized by types, not instantiation point. A class type is not complete or not in itself, it is complete at some point during translation.

A template instantiated on some types must have the exact same semantic in every instantiation.

If not, the behaviour is not defined.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!