Macro code reading as an argument is not performed when std :: map is present

I have a macro used around a code statement to introduce nested exception handling:

#define TRAP_EXCEPTION(statement) \
    try \
    { \
        try{statement} \
        catch(Engine::Exception& e) \
        { \
            throw MyException(e.message()); \
        } \
    }

This works well until in one case compiler errors have occurred. I managed to create a minimal example:

TRAP_EXCEPTION
(
 std::map<MyType, bool> Map;
)
catch(MyException& e)
{
}

This leads to the following errors ... how to fix it (ideally in a macro)?

> error C2143: syntax error : missing '>' before '}'
> error C2976: 'std::map' : too few template arguments
> error C2143: syntax error : missing ';' before '}'
+4
source share
3 answers

Macros do not understand the template parameters (more precisely, angle brackets), they just see ,and think that you have provided two different parameters to the macro. You need to add parentheses:

TRAP_EXCEPTION
(
    (std::map<MyType, bool> Map;)
)

and the macro needs to be changed:

#define UNWRAP(...) __VA_ARGS__

#define TRAP_EXCEPTION(statement) \
    try \
    { \
        try{UNWRAP statement} \
        catch(Engine::Exception& e) \
        { \
            throw MyException(e.message()); \
        } \
    }

, , .

( ), :

#define TRAP_EXCEPTION(...) \
    try \
    { \
        try{ __VA_ARGS__ } \
        catch(Engine::Exception& e) \
        { \
            throw MyException(e.message()); \
        } \
    }

, , ,

TRAP_EXCEPTION
(
    std::map<MyType, bool> Map;
)

.

+5

< > , . , (, ).

, , :

#define TRAP_EXCEPTION(...) \
try \
{ \
    try{__VA_ARGS__} \
    catch(Engine::Exception& e) \
    { \
        throw MyException(e.message()); \
    } \
}

- .

+3

Instead of the trick, __VA_ARGS__you can also use typedef before the macro. The three __VA_ARGS__has some drawbacks.

typedef std::map<MyType, bool> MyMap;

TRAP_EXCEPTION(
  MyMap Map;
)
+3
source

Source: https://habr.com/ru/post/1538059/


All Articles