如何测试一些代码不能在C ++中编译? [英] How to test that some code doesn't compile in C++?
问题描述
可能重复:
单元测试编译时错误
如果它可以写一种单元测试,这将验证给定的代码不编译。
I'm wondering if its possible to write a kind of unit test which will verify that a given code doesn't compile.
例如,我有一个模板类:
For example, I have a template class:
#include <boost/static_assert.hpp>
#include <boost/type_traits/is_base_of.hpp>
struct bar_base {};
template <typename T>
class foo
{
BOOST_STATIC_ASSERT(::boost::is_base_of<T, bar_base>::value);
};
所以,测试应该成功:
struct bar_derived : bar_base {};
foo<bar_derived> f;
,但应该失败:
struct bar_other {};
foo<bar_other> f;
任何想法如何实现这样的行为? (现在,我必须取消注释失败的代码,并手动验证是否有编译错误 - 我想避免这种情况)
Any ideas how to achieve such a behaviour? (For now, I have to uncomment the failing code and verify manually that there are compile errors - I want to avoid that)
推荐答案
Boost有编译测试,他们通过简单地将每个测试放入一个单一的源文件,然后尝试编译每一个。 Boost.Build 支持运行测试的特殊命令,包括测试文件是否编译。
Boost does have compilation tests, and they do this by simply putting each of these tests into a single source-file and then try to compile each of these. Boost.Build supports special commands to run tests, which include testing if a file compiles or not.
这篇关于如何测试一些代码不能在C ++中编译?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!