Rus*_*lan 6 c c++ function function-prototypes
假设有一个库,其中一个版本定义了一个带名称的函数foo,另一个版本的名称已更改为foo_other,但这两个函数仍具有相同的参数和返回值.我目前使用这样的条件编译:
#include <foo.h>
#ifdef USE_NEW_FOO
#define trueFoo foo_other
#else
#define trueFoo foo
#endif
Run Code Online (Sandbox Code Playgroud)
但这需要对库版本进行一些外部检测并设置相应的编译器选项-DUSE_NEW_FOO.我宁愿让代码自动确定它应该调用什么函数,基于它被声明或不被声明<foo.h>.
有没有办法在任何版本的C中实现这一点?
如果没有,切换到任何版本的C++会为我提供任何方法吗?(假设库执行所有需要的操作,如extern "C"标题中的块)?也就是说,我正在考虑以某种方式利用SFINAE,但是对于全局函数而不是方法,这是在链接问题中讨论的.
在 C++ 中,您可以使用表达式 SFINAE 来实现此目的:
//this template only enabled if foo is declared with the right args
template <typename... Args>
auto trueFoo (Args&&... args) -> decltype(foo(std::forward<Args>(args)...))
{
return foo(std::forward<Args>(args)...);
}
//ditto for fooOther
template <typename... Args>
auto trueFoo (Args&&... args) -> decltype(fooOther(std::forward<Args>(args)...))
{
return fooOther(std::forward<Args>(args)...);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
180 次 |
| 最近记录: |