编译时间检查函数是否使用/未使用c ++ [英] Compile time check if a function is used/unused c++

查看:126
本文介绍了编译时间检查函数是否使用/未使用c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在编译时检查某些类的某些函数是否被使用,因此会失败/通过编译过程。

I'd like to check during compile time if some function of some class is used/not used, and accordingly fail/pass the compilation process.

例如,如果函数 F1 在代码中被调用,我想要编译成功,如果函数 F2

For example if function F1 is called somewhere in the code I want the compilation to succeed, and if function F2 is called I want it to fail.

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

Any ideas on how to do that, with usage of preprocessor, templates or any other c++ metaprogramming technique?

推荐答案

如果你愿意修改F2以在函数体中包含一个static_assert,签名的虚拟模板:

You can achieve this with a c++11 compiler provided you are willing to modify F2 to include a static_assert in the function body and add a dummy template to the signature:

#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的呼叫者, a href =http://coliru.stacked-crooked.com/a/6dece4b21df18a95 =nofollow>代码将编译。请参见此答案,了解为什么我们需要模板欺骗,不能简单地插入 static_assert(false) ,);

If there are no callers of F2, the code will compile. See this answer for why we need the template trickery and can't simply insert a static_assert(false, "");

这篇关于编译时间检查函数是否使用/未使用c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆