是否有任何方法可以检查函数是否已声明
Is there any way to check whether a function has been declared?
假设有一个库,其中一个版本定义了一个名称为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,不带任何参数
相关文章:
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 是否有类似std::lower_bound的函数,而不需要排序/分区输入
- 函数作为模板参数,是否对返回类型强制约束
- visual是否可以在c++中创建一个接收无限数量相同类型(或至少相当数量)参数的函数
- 编译器如何在使用SFINAE的函数和标准函数之间确定两者是否可行
- 函数是否可以访问传递给main()的参数
- 是否可以将llvm::FunctionType转换为C/C++原始函数指针
- 在这种情况下,java对象是否可以调用本机函数
- 检查函数返回类型是否与STL容器类型值相同
- 根据某个函数是否存在启用模板
- 在C++中,使用带有 std::optional 参数的函数<T>来表示可选参数是否有意义?
- 无论如何,我可以确定构造函数是否存在吗?
- 是否可以将函数导入命名空间,但不能导出它?
- 返回指向对象的指针的函数调用是否为 prvalue?
- 是否可以依赖函数范围的静态变量来执行程序关闭期间调用的方法?
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 是否有任何建议来统一函数类型限定符并简化可恶的函数类型?
- 在函数范围内在堆栈上分配的数组在离开函数时是否总是被释放?
- 表达式 SFINAE:如何根据类型是否包含具有一个或多个参数的函数来选择模板版本