tags:

views:

118

answers:

3

Suppose I have a C++ macro CATCH to replace the catch statement and that macro receive as parameter a variable-declaration regular expression, like <type_name> [*] <var_name> or something like that. Is there a way to recognize those "fields" and use them in the macro definition?

For instance:

#define CATCH(var_declaration) <var_type> <var_name> = (<var_type>) exception_object;

Would work just like:

#define CATCH(var_type, var_name) var_type var_name = (var_type) exception_object;


As questioned, I'm using g++.

A: 

What compiler are you using? I've never seen this done in the gcc preprocessor, but I can't say for sure that no preprocessor out there can implement this functionality.

What you could do however is run your script through something like sed to do your prepreprocessing so to speak before the preprocessor kicks in.

hhafez
The compiler I'm using is g++. I don't mind using another preprocessor.
freitass
A: 

Hmmm... I'm just guessing, but why don't you try something like this : :)


#define CATCH(varType,varName)  catch(varType& varName) { /* some code here */ }


dempl_dempl
I'm writing macros for that because I can't use the default construct.
freitass
+1  A: 

You can't do it with just macros, but you can be clever with some helper code.

template<typename ExceptionObjectType>
struct ExceptionObjectWrapper {
  ExceptionObjectType& m_unwrapped;

 ExceptionObjectWrapper(ExceptionObjectType& unwrapped) 
 : m_unwrapped(unwrapped) {}

 template<typename CastType>
 operator CastType() { return (CastType)m_wrapped; }
};
template<typename T>
ExceptionObjectWrapper<T> make_execption_obj_wrapper(T& eobj) {
  return ExceptionObjectWrapper<T>(eobj);
}

#define CATCH(var_decl) var_decl = make_exception_obj_wrapper(exception_object);

With these definitions,

CATCH(Foo ex);

should work. I will admit to laziness in not testing this (in my defence, I don't have your exception object test with). If exception_object can only be one type, you can get rid of the ExceptionObjectType template parameter. Further more, if you can define the cast operators on the exception_object itself you can remove the wrappers altogether. I'm guessing exception_object is actually a void* or something though and your casting pointers.

Logan Capaldo