2009-07-05 84 views
0

假设我有一个C++宏CATCH来替换catch语句,并且该宏接收变量声明正则表达式的参数,如<type_name> [*] <var_name>或类似的东西。有没有办法识别这些“字段”并在宏定义中使用它们?是否可以将宏的参数视为正则表达式?

例如:

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

将工作就像:

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

至于质疑,我使用的是G ++。

回答

1

你不能只用宏去做,但你可以巧妙的搭配一些辅助代码。

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

利用这些定义,

CATCH(美孚前);

应该工作。我会承认懒惰不测试这个(在我的防守中,我没有你的异常对象测试)。如果exception_object只能是一种类型,则可以去掉ExceptionObjectType模板参数。此外,如果您可以在exception_object上定义转换运算符,则可以完全删除这些包装。我猜exception_object实际上是一个void *或东西,虽然你的投射指针。

0

你使用什么编译器?我从来没有在gcc预处理器中看到过这一点,但我不能肯定地说没有预处理器可以实现这个功能。

但是你可以做的是,通过类似的sed做你prepreprocessing所以在预处理踢前发言运行脚本。

+0

我使用的编译器是g ++。我不介意使用另一个预处理器。 – freitass 2009-07-05 22:42:25

0

嗯...我只是猜测,但你为什么不尝试是这样的::)


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

+0

我正在写宏,因为我不能使用默认构造。 – freitass 2009-07-08 17:10:06

相关问题