I am looking to define two library with different names that use the same code

141 Views Asked by At

I have a c++ library which has an function called ExampleFunction(). This function is documented and is already in use. Unfortunately, the style of the library requires this function to be called exampleFunction() {initial letter is lowercase}.

I need to keep the old name for backwards compatibility but add the new name as a public function. What is the most efficient way to do this?

I am assuming that adding a definition of:

void exampleFunction() {ExampleFunction();}

is not the best way of solving this and am looking for options.

3

There are 3 best solutions below

1
Kevin On BEST ANSWER

You could rename the existing function that actually has the implementation to exampleFunction(), since that's what it should be. Then, so users of the old name 1) still have working code, and 2) are told that there's a newer function name to use, you can do this:

[[deprecated("Use exampleFunction() instead")]]
inline void ExampleFunction() { exampleFunction(); }

This uses the deprecated attribute from C++14 and later. The performance hit for the wrapper function is either non-existent (if really inlined by the compiler) or negligible.

9
eerorika On

I am assuming that adding a definition of "void exampleFunction() {ExampleFunction(); return;}" is not the best way of solving this

I recommend to not assume such thing. That is a fine way to solve this.

am looking for options.

Another option is to use a function reference (or alternatively a function pointer):

auto& exampleFunction = ExampleFunction;
0
IlCapitano On

As an alternative to other answers, you can use variadic templates, perfect forwarding and decltype(auto).

template<typename ...Args>
[[deprecated("use exampleFunction")]] decltype(auto) ExampleFunction(Args &&...args)
{
    return exampleFunction(std::forward<Args>(args)...);
}

You could define a macro for declaring these functions:

#define def_deprecated_func(old_name, new_name)                          \
template<typename ...Args>                                               \
[[deprecated("use " #new_name)]] decltype(auto) old_name(Args &&...args) \
{                                                                        \
    return new_name(std::forward<Args>(args)...);                        \
}

// ...

def_deprecated_func(ExampleFunction, exampleFunction)

Compile errors won't be great for the deprecated functions, but seeing as you shouldn't use them in the first place, that's not really a compromise.

Note, that this requires you to rename the original function from ExampleFunction to exampleFunction.