[英]How to pass member function as a parameter?
C ++語法正在扼殺我。 我試圖this
+指針傳遞給成員函數:所以我做了以下事情:
template <void(Myclass::*func)()>
static void Myfunction(Myclass* theThis)
{
theThis->*func();
}
這非常有效。
但是現在我想從這個函數傳遞給另一個函數這個成員函數。
template <void(Myclass::*func)()>
static void Myfunction2(Myclass* theThis) // My new function
{
theThis->*func();
}
template <void(Myclass::*func)()>
static void Myfunction(Myclass* theThis)
{
Myfunction2<&(Myclass::*func)>(theThis) // This doesn't compile, the template parameter is probably incorrect
}
但它不編譯,我不知道如何傳遞這個成員函數。
我得到: error C2059: syntax error: '<tag>::*'
編輯:
只是為了說清楚。 我沒有名為func的函數,這只是指向成員函數的指針的名稱
func
已經是你要傳遞的值,所以只需傳遞它:
template <void(Myclass::*func)()>
static void Myfunction2(Myclass* theThis) // My new function
{
(theThis->*func)();
}
template <void(Myclass::*func)()>
static void Myfunction(Myclass* theThis)
{
Myfunction2<func>(theThis);
}
我建議你不要使用指向成員函數作為模板參數。 而是使用更簡單的類型並傳遞該類型的可調用對象作為參數。
這將允許您使用std::bind
綁定到函數,或使用lambda表達式 ,甚至是普通的非成員函數。
也許是這樣的:
template<typename C>
void MyFunction2(C callable)
{
callable();
}
template<typename C>
void MyFunction1(C callable)
{
MyFunction2(callable);
}
要像它一樣使用
MyFunction1(std::bind(&MyClass::TheRealFunction, theThis));
要么
MyFunction1([&theThis]()
{
theThis->TheRealFunction();
});
使用這樣的模板是所有標准庫函數將可調用對象作為參數的常用方法。
您當然可以使用std::function
,然后根本不使用模板:
void MyFunction2(std::function<void()> callable)
{
callable();
}
void MyFunction1(std::function<void()> callable)
{
MyFunction2(callable);
}
用法如上。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.