断言代码不能编译

Assert that code does NOT compile(断言代码不能编译)

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

问题描述

简而言之:

如何编写测试,检查我的类是否不可复制或可复制分配,而只能移动和可移动分配?

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

一般来说:

如何编写测试以确保特定代码不会编译?像这样:

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?

推荐答案

一篇好文章的结尾给出了很好的答案可诊断有效性" by Andrzej Krzemieński:

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

检查给定构造是否编译失败的一种实用方法是从 C++ 外部进行:准备一个带有错误构造的小型测试程序,编译它,然后测试编译器是否报告编译失败.这就是负面"单元测试如何与 Boost.Build 一起工作.有关示例,请参阅此负面测试表单 Boost.Optional 库:optional_test_fail_convert_from_null.cpp.在配置文件中标注为compile-fail,表示只有编译失败才通过测试.

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.

这篇关于断言代码不能编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:断言代码不能编译

基础教程推荐