如何测试某些代码不能在C ++中编译?

Mar*_*dej 5 c++ testing templates unit-testing compilation

可能重复:
单元测试编译时错误

我想知道是否有可能编写一种单元测试来验证给定的代码不会编译。

例如,我有一个模板类:

#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);
};
Run Code Online (Sandbox Code Playgroud)

因此,测试应成功完成:

struct bar_derived : bar_base {};
foo<bar_derived> f;
Run Code Online (Sandbox Code Playgroud)

但应该失败:

struct bar_other {};
foo<bar_other> f;
Run Code Online (Sandbox Code Playgroud)

有什么想法如何实现这种行为?(现在,我必须取消注释失败的代码,并手动验证是否存在编译错误-我想避免这种情况)

Bjö*_*lex 4

Boost 确实有编译测试,他们通过简单地将每个测试放入一个源文件中,然后尝试编译每个测试来实现这一点。Boost.Build支持运行测试的特殊命令,其中包括测试文件是否编译。