Check static_assert in unit test

I would like to make sure that static_assert works as it should in unit test. That is, if I have

class MyClass {static_assert(my_type_trait<T>::value, "error"); };

then in the unit test MyClass<TypeWithTrait> myClass;should β€œpass” and MyClass<TypeWithoutTrait> myClass;should β€œfail”.

Is it possible to do something like this?

+4
source share
2 answers

If you want to verify that something cannot be compiled, you will need to check the external code. Just write a simple file, for example:

#include "MyClass.h"

int main() { 
    MyClass<%T%> m;
}

unit test, %T%. , , , static_assert , .

+3

Barry - , , , . , , , , , .

, static_assert - SFINAE , -. , :

template <class T>
using void_t = void;

template <class T>
struct foo;

template <>
struct foo <double> {};

template <class T, class = void>
struct has_foo_trait : std::false_type {};

template <class T>
struct has_foo_trait<T, void_t<decltype(foo<T>{})>> : std::true_type {};

int main(int, char**) {
  std::cerr << has_foo_trait<int>::value;
  std::cerr << has_foo_trait<double>::value;
  return 0;
}

01. , , static_assert ing , , static_assert, .

, , , , , . "" void_t . SFINAE true has_foo_trait, . , , . . , .

-1

Source: https://habr.com/ru/post/1627857/


All Articles