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.
这篇关于断言代码不能编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:断言代码不能编译


基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 我有静态或动态 boost 库吗? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01