Max*_*rin 5 c++ templates code-generation metaprogramming c-preprocessor
我想在编译期间检查是否使用/不使用某些类的某些函数,并因此失败/通过编译过程.
例如,如果函数F1
在代码中的某处被调用,我希望编译成功,如果函数F2
被调用,我希望它失败.
有关如何使用预处理器,模板或任何其他c ++元编程技术的任何想法?
小智 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
}
Run Code Online (Sandbox Code Playgroud)
如果没有F2的调用者,代码将编译.请参阅此答案,了解为什么我们需要模板技巧,而不能简单地插入一个static_assert(false, "");