断言代码不能编译

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.

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)