2012-11-28 39 views
0

我经常遇到黑客喜欢有没有办法阻止在编译期间使用未实现的函数?

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

我想这是一个不好的做法,但旁白:
有没有办法做到在编译期间同样的事情,但前提是功能时(又名如果这是未使用的编译应该成功)。

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

+0

如果一个函数是_not implemented_(如在,未声明但未定义),那么你将得到一个链接时间错误。在这种情况下,你的功能被实现,并且具有定义良好的行为。 – Chad

回答

4

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

如果是在一个基类中声明的虚函数,那么你就无法控制在编译时调用,这样的话你唯一的选择是一些运行时错误或异常。

+0

是的例子我看到的是虚拟成员funcs。 :) – NoSenseEtAl

6

如果除去实现完全和只有函数声明,就会出现链接错误,这是基本的编译时间。不幸的是,链接器错误往往是丑陋而难以追查的,但在调用尚未实现的函数的情况下,我认为它们非常易于管理。

+2

链接器错误不是基本*编译时。这是链接时间。 – Nawaz

+1

如果函数是虚拟的并且某个基类实现了该怎么办? –

0

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

也许不是你脑子里的东西,但这样做,如果任何试图使用它会产生一个编译时错误,并将得到的代码应该是相同的一个空函数,这通常是优化掉。

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)" ([email protected]@@SAXXZ) referenced in function "[blahblahblah]" 

注意, '引用的函数' 是有在MSVC++。我没有在其他编译器中测试过它。

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

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

相关问题