static_assert inside/outside class definition

后端 未结 1 1784
清酒与你
清酒与你 2021-01-04 00:26

Why does static_assert need to be out side of the class definition?

Failing code

#include 

class A
{
public:
            


        
相关标签:
1条回答
  • 2021-01-04 00:54

    As far as the placement of static_assert itself is concerned both versions of your code are valid. So, no, static_assert does not need to be outside of class definition. Formally static_assert is a declaration. It is allowed wherever declarations are allowed.

    The problem you are having has nothing to do with static_assert itself.

    The problem here is that the expression that you use as the argument of your static_assert (std::is_nothrow_move_constructible) requires the class type to be complete to work properly. But inside the definition of class A class type A is not complete yet, which makes your argument expression invalid. This is why your static_assert works as intended only outside the class definition, where A is complete. However, this is entirely about proper usage of std::is_nothrow_move_constructible, not about static_assert itself.

    Note, that inside member function bodies class type is seen in its entirety, as complete type, even if the member function is defined inside the class definition. Using this feature you can rewrite your code as

    class A
    {
    public:
        A(A&&) noexcept {
          static_assert(std::is_nothrow_move_constructible<A>::value, "ERROR"); 
        }
    };
    

    and std::is_nothrow_move_constructible<A> will produce the proper result.

    0 讨论(0)
提交回复
热议问题