2009-07-05 87 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

相關問題