编译时间检查函数是否使用/未使用c ++

时间:2013-09-15 14:53:13

标签: c++ templates c-preprocessor metaprogramming code-generation

我想在编译期间检查是否使用/不使用某个类的某些函数,并因此失败/通过编译过程。

例如,如果在代码中的某处调用函数F1,我希望编译成功,如果调用函数F2,我希望它失败。

关于如何使用预处理器,模板或任何其他c ++元编程技术的任何想法?

2 个答案:

答案 0 :(得分:5)

您可以使用c ++ 11编译器实现此目的,前提是您愿意修改F2以在函数体中包含static_assert并在签名中添加虚拟模板:

#include <type_traits>

void F1(int) {    
}

template <typename T = float>
void F2(int) {
    static_assert(std::is_integral<T>::value, "Don't call F2!");
}

int main() {
 F1(1);  
 F2(2);  // Remove this call to compile
}

如果没有F2的来电者,the code will compile。请参阅this answer了解我们为什么需要模板技巧,而不能简单地插入static_assert(false, "");

答案 1 :(得分:1)

不是一个非常模板化的解决方案,但您可以依赖编译器的弃用属性,如果在任何地方使用函数,它将生成警告。

如果是MSVC,则使用__declspec(deprecated)属性:

__declspec(deprecated("Don't use this")) void foo();

G ++:

void foo() __attribute__((deprecated));

如果您将“将警告视为错误”编译选项(您通常应该这样做),您将获得所需的行为。

int main() 
{
    foo(); // error C4966: 'foo': Don't use this
    return 0;
}
相关问题