是否有任何方法可以检查函数是否已声明

Is there any way to check whether a function has been declared?

本文关键字:是否 函数 声明 检查 任何 方法      更新时间:2023-10-16

假设有一个库,其中一个版本定义了一个名称为foo的函数,另一个版本将名称更改为foo_other,但这两个函数仍然具有相同的参数和返回值。我目前使用的条件编译是这样的:

#include <foo.h>
#ifdef USE_NEW_FOO
#define trueFoo foo_other
#else
#define trueFoo foo
#endif

但是这需要一些库版本的外部检测,并设置相应的编译器选项,如-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)...);
}

如果你静态地链接到一个函数,在大多数c++版本中,函数的名称被"修改"以反映它的参数列表。因此,当一个程序使用过期的.hpp文件试图静态地链接到库时,将导致一个"未知符号"链接错误。

在C语言中,没有任何类型的元数据来指示任何导出函数的参数列表实际上是

实际上,我认为,您只需要确保用于链接到库的.h.hpp文件实际上反映了您正在使用的库的任何版本中的相应目标代码。您还需要确保Makefile(或"auto-make"进程)将正确识别应用程序中链接到该库的所有模块,因此在对其进行任何更改时必须重新编译这些模块。(如果是我,我会重新编译整个应用程序。)总之,必须确保这个问题不会发生。

在c++中可以这样做:

#include <iostream>
#include <type_traits>
//#define DEFINE_F
#ifdef DEFINE_F
void f()
{
}
#endif
namespace
{
    constexpr struct special
    {
      std::false_type operator()() const;
    }f; 
}
struct checkForF
{
    static const constexpr auto value = std::conditional< std::is_same<std::false_type, decltype(::f())>::value, std::false_type, std::true_type >::type();
};
int main()
{
    std::cout << checkForF::value << std::endl;
}

ideone

请注意,我只处理f,不带任何参数

相关文章: