static assert that template typename T is NOT complete?

后端 未结 2 1365
你的背包
你的背包 2020-12-31 16:47

Is there a way to static_assert that a type T is Not complete at that point in a header? The idea is to have a compile error if someone adds #includes down

2条回答
  •  长情又很酷
    2020-12-31 17:04

    Here is a function using expression SFINAE based on chris proposal which allows checking whether a type is complete yet.
    My adoption needs no includes, errors-out when the required argument is missing (hiding the argument was not possible) and is suitable for C++11 onward.

    template
    constexpr auto is_complete(int=0) -> decltype(!sizeof(T)) {
        return true;   
    }
    
    template
    constexpr bool is_complete(...) {return false;}
    

    And a test-suite:

    struct S;
    
    bool xyz() {return is_complete(0);}
    
    struct S{};
    
    #include 
    int main() {
        std::cout << is_complete(0) << '\n';
        std::cout << xyz() << '\n';
        std::cout << is_complete(0);
    }
    

    Output:

    1
    0
    1
    

    See live on coliru

提交回复
热议问题