How to test that some code doesn't compile in C++? [duplicate]

一笑奈何 提交于 2020-01-13 10:54:29

问题


Possible Duplicate:
Unit test compile-time error

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);
};

So, the test should succeed with:

struct bar_derived : bar_base {};
foo<bar_derived> f;

but should fail with:

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)


回答1:


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.




回答2:


The gist of it would be that you would run a normal "should fail" unittest, but instead of running your compiled program, you run a compiler on an example that should fail.

Eg on gtest, this would be a "death test" on the compiler. http://code.google.com/p/googletest/wiki/V1_6_AdvancedGuide#Death_Tests



来源:https://stackoverflow.com/questions/9003061/how-to-test-that-some-code-doesnt-compile-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!