[英]How can I use decltype to get the address of some class type's member function?
假設以下代碼:
class MyTest
{
public:
void CallFoo()
{
}
MyTest()
{
std::function<void()> func = &decltype(*this)::CallFoo;
}
};
int main()
{
MyTest t;
}
我那里不會編譯,但是從本質decltype
,我需要能夠使用decltype
來獲取*this
類型的成員函數的地址。 通常,您只需要執行&MyTest::CallFoo
。
這可能嗎? 如果是這樣,正確的語法是什么?
你可以做
&std::remove_pointer_t<decltype(this)>::CallFoo
或在C ++ 11中(抱歉,剛剛注意到的標記)
&std::remove_pointer<decltype(this)>::type::CallFoo
您所擁有的問題是decltype(*this)
提供了MyTest&
而不是MyTest
因為*this
是一個左值。
但是, std::function<void()>
不起作用,因為需要使用MyTest*
調用MyTest
的非靜態成員函數來充當this
。 如果希望調用者指定對象,則可以使用std::function<void(MyTest*)>
或std::function<void(decltype(this))>
。 如果您想綁定this
,則可能應該只使用lambda,這要容易得多:
auto func = [this]{ CallFoo(); };
警告 :包含一個宏。 負責任地使用。
使用以下宏可以使decltype
通過引用“合理地”工作。
template<class T> struct TypeOf { typedef typename std::remove_reference<T>::type type; };
#define TYPE(x) TypeOf<decltype(x)>::type
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.