我正在嘗試傳遞系結的成員函式,std::function同時將呼叫隱藏std::bind_front在基類中。最小的例子:
#include <functional>
static void runIt(std::function<void()> f) { f(); }
template<typename T>
struct Base {
using PFn = void (T::*)();
void run(PFn fun) { runIt(std::bind_front(fun, this)); }
};
struct Derived : Base<Derived> {
void main() { run(&Derived::func); }
void func() {}
};
不幸的是,編譯器不喜歡它:
static void runIt(std::function<void()> f)
No matching function for call to 'runIt' clang(ovl_no_viable_function_in_call)
test.cpp(12, 19): In instantiation of member function 'Base<Derived>::run' requested here
test.cpp(3, 13): Candidate function not viable: no known conversion from 'std::__perfect_forward_impl<std::__bind_front_op, std::__tuple_types<void (Derived::*)(), Base<Derived> *>, std::__tuple_indices<0, 1>>' to 'std::function<void ()>' for 1st argument
我錯過了什么?
uj5u.com熱心網友回復:
你不能std::invoke(fun, this)因為thisis 是型別Base<Derived>*并且函式指標是型別void (Derived::*)()(并且Derived不是 的基礎Base<Derived>,而是相反)。
向上轉換指向成員函式的指標或指向物件的指標。最好是物件指標:
runIt(std::bind_front(fun, static_cast<T*>(this)));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/515424.html
上一篇:除錯異步CoreData呼叫
