断言code不编译 [英] Assert that code does NOT compile

查看:115
本文介绍了断言code不编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简而言之:

如何写一个测试,来检查我的类是不可拷贝或复制分配的,但仅仅是可移动的移动可分配?

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

一般来说:

如何写一个测试,这可以确保一个特定的code的的编译?像这样的:

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;
}

我猜是与SFINAE,但是否有一些现成的解决方案,也许在助推?

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

推荐答案

一个很好的答案在一个伟大的文章的结尾给出的可诊断有效性由安杰Krzemieński:

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

要检查是否给定的构造编译失败的实用的方法是从外部C ++做到这一点:如果编译器报告编译失败$有错的构造p $ ppare一个小的测试程序,编译和测试。这是负面的单元测试如何与Boost.Build工作。举一个例子,看看形式Boost.Optional库这种负面测试:optional_t​​est_fail_convert_from_null.cpp。在配置文件中被注释为编译失败,这意味着如果编译失败的测试只有通过了。

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.

这篇关于断言code不编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆