断言代码不能编译

2023-07-20C/C++开发问题
3

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

问题描述

简而言之:

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

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.

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

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6