簡體   English   中英

將指針和成員指針連接到函數指針

[英]Joining a pointer and member pointer into a function pointer

請考慮以下代碼:

class MyClass{
public:
    void MyFunc(int x){
        std::cout << x << std::endl;
    }
};

int main(){
    MyClass* class_ptr = new MyClass();
    void (Myclass::*member_func_ptr)(int) = &MyClass::MyFunc;

    // This should output '5'.
    (class_ptr->*member_func_ptr)(5);

    /* ??? */

    // I want the following to output '5' exactly the same way as previous call.
    func_ptr(5);
}

我應該如何完成這段代碼讓func_ptr(...)*class_ptr調用MyFunc?

如果有可能,我希望以某種方式MyClass*void (Myclass::*)(int)加入到void (*)(int)

如果沒有,我希望巧妙地使用std::mem_fnstd::function (或其他功能實用程序)可以解決問題。

理想情況下,我想要一個C ++ 11解決方案(因為例如std::mem_fun現在已被棄用)。

你不能得到一個普通的函數指針,但你可以使用bind或lambda獲得一個函數對象:

auto bound = std::bind(member_func_ptr, class_ptr, std::placeholders::_1);
auto lambda = [=](int x){return (class_ptr->*member_func_ptr)(x);}

bound(5);  // should output 5
lambda(5); // should output 5 too

如果需要,這兩個都可以轉換為std::function<void(int)>

您無法從成員指針和對象指針創建函數指針。 您可以獲得的是具有相同調用符號的函數對象,例如,使用std::bind()

std::bind(member_func_ptr, class_ptr, _1)

您可以使用此函數對象進行初始化,例如, std::function<void(int)>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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