0

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__)

Hun Su
  • 13
  • 4

1 Answers1

0

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.

Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85
  • Thanks for answering. I have tried and it works in vs2015 but failed in vs2010. I wonder is there any other way that fits the vs2010? – Hun Su Dec 18 '20 at 07:34
  • Does vs2010 support variadic templates at all? E.g. does this compile `template void f(Args&&... args) {}` – Igor Tandetnik Dec 18 '20 at 12:21
  • The answer is no. VS2010 does not support templates in this format. – Hun Su Dec 19 '20 at 00:40
  • Well, you know the signature of `API1`, I presume. Rather than making `API1Helper` a template, make it a normal function with parameters matching those of API1, plus `file` and `line`. – Igor Tandetnik Dec 19 '20 at 00:55