有没有办法防止在编译期间使用未实现的函数?

时间:2012-11-28 15:57:39

标签: c++ compile-time

经常遇到像

这样的黑客攻击
//lets say this is some class that still doesnt support...
//...all the functionality that it should based on the design docs
void MyClass::MyFunction()
{
  throw std::exception("not implemented");
}

我想这是一种不好的做法,但除此之外:
有没有办法在编译期间做同样的事情,但只有在使用函数时(如果它是未使用的编译应该成功)。

编辑:我也对虚拟内存功能感兴趣。

4 个答案:

答案 0 :(得分:6)

如果完全删除实现并且只有函数声明,则会出现链接器错误,这基本上是编译时间。不幸的是,链接器错误有一种丑陋和难以追踪的倾向,但在调用尚未实现的功能的情况下,我认为它们非常容易管理。

答案 1 :(得分:4)

如果它是非虚函数,那么你可以简单地注释掉定义。

如果它是在基类中声明的虚函数,那么您无法在编译时控制调用,因此您唯一的选择是某些运行时错误或异常。

答案 2 :(得分:1)

老问题,但仍然......

我为此使用了几个简单的助手。它会给出一个相当可读的错误链接时间:

// Not implemented is not implemented :-)thing, it'll break:
struct NotImplHelper { static void notimplemented(); };
#define notimplemented() NotImplHelper::notimplemented();
#if defined(DEBUG) || defined(_DEBUG)
#define notimplementedvirtual() throw std::exception();
#else
#define notimplementedvirtual() static_assert(false, "You should implement virtual function calls before moving to production.");
#endif

用法:

//lets say this is some class that still doesnt support...
//...all the functionality that it should based on the design docs
void MyClass::MyFunction()
{
    notimplemented();
    // or notimplementedvirtual() if MyFunction() is virtual... 
}

<强>理由:

恕我直言,如果您在程序中使用某个功能,它应该可用。当您尝试编译尚未实现的内容时,它应该给出编译时或链接时错误。

F.ex。,在MSVC ++中,这将给出:

1>Test.obj : error LNK2019: unresolved external symbol "public: static void __cdecl NotImplHelper::notimplemented(void)" (?notimplemented@NotImplHelper@@SAXXZ) referenced in function "[blahblahblah]"

请注意,MSVC ++中存在“引用函数”。我还没有在其他编译器中测试它。

对于未实现的虚函数调用,您可以使用它来抛出异常。在开发过程中没有在调试器中实现这些功能很好 - 但是,当一些事情变得严重时,这些可能会被您的程序调用,因此它们应该可用。 static_assert确保后者。 (所以:结合任何持续集成包,它基本上都会失败。)

显然,大多数人会意外混淆notimplementednotimplementedvirtual。实际上这不是一个大问题:一个简单的解决方案是始终使用前者,除非你想摆脱错误,因为它是一个WIP。

答案 3 :(得分:0)

我能想到的最简单的解决方案是评论未实现的功能。

也许不是你的想法,但是这样做会产生编译时错误,如果有人试图使用它,结果代码应该与空函数相同,通常会对其进行优化。

相关问题