我希望在编译期间检查某个类的某个函数是否被使用,然后根据情况通过/未通过编译。
例如,如果代码中有调用
有没有什么想法可以使用预处理器、模板或其他c++元编程技术来实现?
例如,如果代码中有调用
F1
函数的地方,我希望编译成功;如果调用F2
函数则希望编译失败。有没有什么想法可以使用预处理器、模板或其他c++元编程技术来实现?
F1
函数的地方,我希望编译成功;如果调用F2
函数则希望编译失败。如果您愿意修改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
}
static_assert(false, "");
。F2
的旧实现。 - Angew is no longer proud of SOstatic_assert
)。我想这仍然足以实现“如果调用F2
则出现编译时错误”的效果。 - Angew is no longer proud of SOF2(int)
转换为模板会影响重载解析。突然之间,F2(something)
可能会调用不同的F2
。 - 463035818_is_not_a_number这不是一个非常模板化的解决方案,但您可以依赖编译器的“deprecated”属性,如果某个函数在任何地方被使用,它将生成警告。
在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;
}
-Wunused-function
只会警告非内联static
函数)。在链接器标志中也没有找到合适的内容。你可能需要让链接器创建一个映射文件,如果它包含该信息,则解析该文件并发出构建过程错误。 - Some programmer dude