2010-03-13 35 views
0

我想寫一個宏,使C++中的回調具體使用更容易。我所有的回調函數都是成員函數,它們將以this作爲第一個參數,第二個類型從一個公共基類繼承。宏,以提高回調註冊的可讀性

通常的路要走是:

register_callback(boost::bind(&my_class::member_function, this, _1)); 

我很想寫:

register_callback(HANDLER(member_function)); 

注意,它總是在同一個類中使用。

即使typeof被認爲是一種不好的做法,這聽起來像是一個很好的解決方案,因爲缺少__class__宏來獲取當前類名。

下面的代碼工作:

typedef typeof(*this) CLASS; 
boost::bind(& CLASS :: member_function, this, _1)(my_argument); 

,但我不能在其中將作爲參數傳遞給register_callback宏中使用此代碼。

我已經試過:

#define HANDLER(FUN)           \ 
    boost::bind(& typeof(*this) :: member_function, this, _1); 

不的原因,我不明白工作。引用GCC文檔:

A typeof -construct可以在任何可以使用typedef名稱的地方使用。

我的編譯器是GCC 4.4,即使我喜歡標準的東西,也可以接受GCC特定的解決方案。

回答

1

您的問題可能是該類型的收益my_class&。這似乎與boost::remove_reference工作:

#include <boost/bind.hpp> 
#include <boost/type_traits.hpp> 
#include <iostream> 

struct X 
{ 
    void foo(int i) { std::cout << i << '\n'; } 
    void bar() {boost::bind(&boost::remove_reference<typeof(*this)>::type::foo, this, _1)(10); } 
}; 

int main() 
{ 
    X x; 
    x.bar(); 
} 

這可能是更容易移植到使用BOOST_TYPEOF,和C++ 0x中decltype

+0

謝謝。我將仔細看看Boost.TypeTraits,它看起來像是許多模板元編程問題的聰明答案。 – 2010-03-13 18:03:23

相關問題