如果該函數不是static
,則不能將其輸入傳遞給接受非成員函數指針的函數。
考慮到一個非static
成員函數有一個暗指向ClassName
的指針作爲它的第一個參數,它指向了調用成員函數的對象。
struct X
{
static void foo() { } // Does not have an implicit "this" pointer argument
void bar() { } // Has an implicit "this" pointer argument
};
int main()
{
void (*f)() = &X::foo; // OK: foo is static
void (*g)() = &X::bar; // ERROR! bar is non-static
}
在這裏,甚至沒有std::bind()
會的工作,因爲結果是無法轉換爲一個函數指針。 Lambdas可以轉換爲函數指針,但前提是它們不捕獲(而且這裏的lambda需要捕獲該對象來調用成員函數)。
因此,唯一的(醜陋的)解決方法是具有全局適配器函數,該函數在通過全局指針變量可用的對象上調用成員函數。
struct X
{
void bar() { }
};
void function_taking_a_function_pointer(void (*f)())
{
// Do something...
f();
}
X* pX = nullptr;
void bar_adapter()
{
pX->bar();
}
int main()
{
X x; // Some object I want to invoke the member function bar() on...
pX = &x; // Set the global pointer and invoke the function...
function_taking_a_function_pointer(bar_adapter);
}
如果你願意,你可以讓這個稍微靈活轉動bar_adapter
成函數模板,並通過指針到成員函數:全局指針變量調用函數之前設置作爲一個模板參數:
template<typename T, void (T::*mf)()>
void adapter()
{
(pX->*mf)();
}
這裏是你會怎麼使用它:最後
#include <iostream>
struct X
{
void foo() { std::cout << "X::foo()" << std::endl; }
void bar() { std::cout << "X::bar()" << std::endl; }
};
void function_taking_a_function_pointer(void (*f)())
{
// Do something...
f();
}
X* pX = nullptr;
template<typename T, void (T::*mf)()>
void adapter()
{
(pX->*mf)();
}
int main()
{
X x; // Some object I want to invoke the member function bar() on...
pX = &x; // Set the global pointer and invoke the function(s)...
function_taking_a_function_pointer(adapter<X, &X::foo>);
function_taking_a_function_pointer(adapter<X, &X::bar>);
}
,她e是live example。
你得到一個錯誤。它有什麼錯誤? – 0x499602D2 2013-03-24 14:30:01
我正在使用Visual Studio 2012編譯器。我會把編譯器錯誤置於我的問題中。 – 2013-03-24 14:31:36
抱歉,錯誤的編譯器錯誤一開始,現在它的權利 – 2013-03-24 14:41:34