【问题标题】:How to test that some code doesn't compile in C++? [duplicate]如何测试某些代码不能在 C++ 中编译? [复制]
【发布时间】:2012-01-25 12:54:44
【问题描述】:

可能重复:
Unit test compile-time error

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

例如,我有一个模板类:

#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;

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

【问题讨论】:

    标签: c++ unit-testing templates testing compilation


    【解决方案1】:

    Boost 确实有编译测试,他们只需将这些测试中的每一个放在一个源文件中,然后尝试编译它们中的每一个即可。 Boost.Build 支持special commands to run tests,包括测试文件是否编译。

    【讨论】:

      【解决方案2】:

      它的要点是您将运行一个正常的“应该失败”的单元测试,但不是运行已编译的程序,而是在应该失败的示例上运行编译器。

      例如,在 gtest 上,这将是对编译器的“死亡测试”。 http://code.google.com/p/googletest/wiki/V1_6_AdvancedGuide#Death_Tests

      【讨论】:

      • 怎么做?该链接没有提到这一点。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-03
      • 1970-01-01
      • 2011-03-01
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      相关资源
      最近更新 更多