gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:25:07 25 4
gpt4 key购买 nike

我想在编译期间检查是否使用/未使用某些类的某些函数,并相应地使编译过程失败/通过。

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

关于如何通过使用预处理器、模板或任何其他 c++ 元编程技术来做到这一点有什么想法吗?

最佳答案

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

#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, "");

关于c++ - 编译时检查函数是否被使用/未使用 c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18813731/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com