簡體   English   中英

如何使用decltype獲取某個類類型的成員函數的地址?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM