How to keep original function return value after using Variadic Macros?

44 Views Asked by At

It is a VS2010 C++ project. I have a list of APIs:

  1. int a = API1("para1", "para2", ...);

  2. double a = API2("para1", "para2", ...);

  3. float a = API3("para1", "para2", ...);

Now, I need to add a new API, APINEW(). As long as above APIs are run, APINEW need to called as follow. Therefore, I decided to use the Variadic Macros as shown below:

#define newAPI1(...) ( API1(__VA_ARGS__); APINEW() )

#define newAPI2(...) ( API2(__VA_ARGS__); APINEW() )

#define newAPI3(...) ( API3(__VA_ARGS__); APINEW() )

However, I will not correctly get the return value from my API1, API2 and API3.

I am trying to use the following code since I know the marco will always return the last item, but it cannot pass the compile.

#define newAPI1(...) ( {auto a = API1(__VA_ARGS__); APINEW(); a} )

I wonder is there a way that can make it correct? (The reason I use new name (e.g. newAPI1) is to avoid comflict because in the project, it may have other macros that overload the existing API1, API2 and API3.)

Another question: is there a way to pass the combination of

  1. first parameter of __VA_ARGS__
  2. __FUNCTION__
  3. __LINE__

into the APINEW parameter => APINEW(first parameter of __VA_ARGS__ + __FUNCTION__ + __LINE__)

1

There are 1 best solutions below

4
On

Something along these lines, perhaps.

template <typename FirstArg, typename... Args>
auto API1Helper(const char* file, int line, FirstArg&& first_arg, Args&&... args) {
  auto ret = API1(first_arg, std::forward<Args>(args)...);
  APINEW(first_arg, file, line);
  return ret;
}

#define newAPI1(...) API1Helper(__FILE__, __LINE__, __VA_ARGS__)

Though this may require a compiler newer than VS2010.