我想知道我是否可以编写一个 .cpp 文件来尝试实例化一个抽象类:
// file: test_ensure_A_is_abstract.cpp
class A { void foo() = 0; };
int main() { new A; }
// a simple shell script would look like this, but that is missing all the
// options cmake normally generates (-I, -g, -c, -o, ...)
if g++ test_ensure_A_is_abstract.cpp; then exit 1; else exit 0; fi
然后让 cmake 尝试编译它。我在这里的意思是,我想证明该类是抽象的并且仍然是抽象的,因此永远无法实例化它。
我知道如何创建有效目标,但我想知道是否有办法为已知无效的目标运行 cmake?以前有人这样做过吗?
更新:
根据 steveire 的回答和下面的评论,我编写了自己的模块来完成工作并确保该类确实是抽象的(而不是指望任何编译器失败都表明是抽象类。)所以我们必须匹配特定错误的错误消息。我支持其中的 4 个,其中 2 个明确使类抽象(至少一个函数是纯虚拟的),另外 2 个将 protected 和私有(private)构造函数视为一种抽象类(就像抽象类一样,你不能做一个新的 <类名>.
您可以在 Snap 中找到该模块! C++ git 在这里:
https://sourceforge.net/p/snapcpp/code/ci/master/tree/snapCMakeModules/Modules/
它被命名为CheckCXXAbstractClass.cmake。
最佳答案
http://www.cmake.org/cmake/help/v3.0/command/try_compile.html
http://www.cmake.org/cmake/help/v3.0/module/CheckCXXSourceCompiles.html
check_cxx_source_compiles(
"class A { void foo() = 0; };\nint main() { new A; }"
BUILT_ABSTRACT
)
if (BUILT_ABSTRACT)
message(FATAL_ERROR "A can be instantiated, but should be abstract.")
endif()
如果您适本地设置了 CMAKE_REQUIRED_INCLUDES
变量,您可以#include "A"
。
关于c++ - 使用 cmake : how could I write a test to verify that a class is abstract?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23977313/