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

后端 未结 2 526
借酒劲吻你
借酒劲吻你 2021-01-18 18:02

I want to achieve behavior like sizeof(complete_type) will return real sizeof, and sizeof(incomplete_type) - will be just 0

I need this to provide extended run time

2条回答
  •  温柔的废话
    2021-01-18 18:08

    Use SFINAE, as usual. This is one possible implementation:

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

    Example:

    #include 
    
    struct F;
    struct G {};
    
    int main()
    {
        printf("%d %d\n", is_complete::value, is_complete::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)

提交回复
热议问题