简体   繁体   中英

Throwing function-like variadic macro wrapping, replacing thrown exception

Suppose I have a third party library that provides a function-like ThirdPartyMacro macro that is:

  1. Variadic and accepts arbitrary tokens, not just well formed c++ expressions. After parsing the arguments ThirdPartyMacro extracts some tokens that it assumes to be identifiers denoting variables in the scope of it's invocation, and uses them as such.
  2. Evaluates to some value of a known type.
  3. May throw an exception of type ThirdPartyException

I want to wrap this up by writing a macro MyMacro that will behave exactly like ThirdPartyMacro but throw MyException whenever ThirdPartyMacro would throw ThirdPartyException .

Is it possible? If so, how?

Not that due to (1) MyMacro cannot be a function, as it's arguments are not something that can be passed as function parameters.

A lambda will help:

#define MyMacro(...) \
   [&]{ try { return ThirdPartyMacro(__VA_ARGS__); } \
        catch( const ThirdPartyException& e ) \
        { throw MyException( e.what() ); } }()

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