简体   繁体   中英

C++ namespace as a macro value

I have simple delegate functions in my C++ test code. Since I cannot include the original implementation .cpp files(embedded ones), I use delegate .cpp file in the tests that are running on PC. My idea is to simply use the same macro as a body for the implementation, except the parentheses () and arguments which will supplied according to the signature.

I tried something like:

void Flash::init()
{
   DELEGATE_DESTINATION();
}

bool Flash::write(args)
{
   DELEGATE_DESTINATION(args);
}

bool Flash::read(args)
{
   DELEGATE_DESTINATION(args);
}

Where

void Flash::init()
bool Flash::write(args)
bool Flash::read(args)

Are identical to the ones in the embedded project implementation ones. In the test files I simply relay the call to the fake implementations. One possible solution would be to already include the signature and implementation in the fake classes not using relaying, I know.

I am having hard time figuring out the macro. I tried something like:

#define FAKE_PREFIX             fakes::device::Flash::
#define DELEGATE_DESTINATION    FAKE_PREFIX##__FUNCTION__

Which expands to FAKE_PREFIX__FUNCTION__

Well then after going through C Preprocessor, Stringify the result of a macro I can get only fakes expanding in place.

My goal would be to have a result like

fakes::device::Flash::init

and so on for read and write .

What you want to do can be done far simpler. You don't need the full power of the pre-processor:

  1. You don't concatenate tokens ( :: is not part of a valid token). You just need to print one macro next to another.

  2. _FUNCTION_ isn't a pre-processor macro, it's a string literal ( in gcc and other compilers).

So to do what you want, you need to pass the function name into your macro:

#define FAKE_PREFIX fakes::device::Flash::
#define DELEGATE_DESTINATION(func)  FAKE_PREFIX func

Then you define your functions, like this:

bool Flash::write(args)
{
  DELEGATE_DESTINATION(write)(args);
}

It's all live here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM