Search code examples
c++c++11boostcompiler-errorssfinae

Assert that code does NOT compile


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?

In general:

How to write a test, that makes sure that a specific code does not compile? Like this:

// Movable, but non-copyable class
struct A
{
  A(const A&) = delete;
  A(A&&) {}
};

void DoCopy()
{
  A a1;
  A a2 = a1;
}

void DoMove()
{
  A a1;
  A a2 = std::move(a1);
}

void main()
{
  // How to define these checks?
  if (COMPILES(DoMove)) std::cout << "Passed" << std::endl;
  if (DOES_NOT_COMPILE(DoCopy)) std::cout << "Passed" << std::endl;
}

I guess something to do with SFINAE, but are there some ready solutions, maybe in boost?


Solution

  • A good answer is given at the end of a great article "Diagnosable validity" by Andrzej Krzemieński:

    A practical way to check if a given construct fails to compile is to do it from outside C++: prepare a small test program with erroneous construct, compile it, and test if compiler reports compilation failure. This is how “negative” unit tests work with Boost.Build. For an example, see this negative test form Boost.Optional library: optional_test_fail_convert_from_null.cpp. In configuration file it is annotated as compile-fail, meaning that test passes only if compilation fails.