Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Suppose there's a library, one version of which defines a function with name foo, and another version has the name changed to foo_other, but both these functions still have the same arguments and return values. I currently use conditional compilation like this:

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

But this requires some external detection of the library version and setting the corresponding compiler option like -DUSE_NEW_FOO. I'd rather have the code automatically figure what function it should call, based on it being declared or not in <foo.h>.

Is there any way to achieve this in any version of C?

If not, will switching to any version of C++ provide me any ways to do this? (assuming the library does all the needed actions like extern "C" blocks in its headers)? Namely, I'm thinking of somehow making use of SFINAE, but for a global function, rather than method, which was discussed in the linked question.

like image 337
Ruslan Avatar asked Jun 04 '15 13:06

Ruslan


1 Answers

In C++ you can use expression SFINAE for this:

//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)...);
}
like image 85
TartanLlama Avatar answered Sep 29 '22 00:09

TartanLlama