Assert that code does NOT compile

后端 未结 6 941
长发绾君心
长发绾君心 2020-12-03 04:54

In short:

How to write a test, that checks that my class is not copyable or copy-assignable, but is only moveable and move-assignable?

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-03 05:46

    for example this std::is_nothrow_move_assignable::value returns true in compile-time.

    for more checkers see https://en.cppreference.com/w/cpp/types#Supported_operations

    i recommend using it along with static_assert, see https://en.cppreference.com/w/cpp/language/static_assert

    now in general i was trying to check if i can call a specific method on some object. this boils down to "assert if this code compiles" and there is a neat and short way to check it.

    template using canCallPrintYesOn = decltype(::std::declval().printYes());
    
    constexpr bool canCallPrintYesOn_MyType = std::experimental::is_detected::value;
    
    static_assert(canCallPrintYesOn_MyType, "Should be able to call printYes(void) on this object");
    

    if this fails, you get compile error with above string

提交回复
热议问题