#include <utility>
class Base {
public:
virtual ~Base() {}
virtual void base() {}
};
class Derived : public Base {
public:
virtual void derived() {}
};
template<typename... Params>
using MemberFuncPtr = void(Derived::*)(Params...);
template<typename... Params, typename... Args>
void wrapper(MemberFuncPtr<Params...> ptr, Args&&... args)
{
Derived* d = new Derived();
(d->*ptr)(std::forward<Args>(args)...);
delete d;
}
int main()
{
wrapper(&Derived::derived);
wrapper(&Derived::base);
return 0;
}
試圖運行該代碼(GCC 7.0)給了我以下錯誤:模板參數,它指向類成員函數
prog.cc: In function 'int main()':
prog.cc:33:27: error: no matching function for call to 'wrapper(void (Base::*)())'
wrapper(&Derived::base);
^
prog.cc:18:6: note: candidate: template<class ... Params, class ... Args> void wrapper(MemberFuncPtr<Params ...>, Args&& ...)
void wrapper(MemberFuncPtr<Params...> ptr, Args&&... args)
^~~~~~~
prog.cc:18:6: note: template argument deduction/substitution failed:
prog.cc:33:27: note: mismatched types 'Derived' and 'Base'
wrapper(&Derived::base);
^
我真的不明白,爲什麼從基類方法是問題?這也是派生類的一種方法。我已經完成了簡單的測試,其中我分配了Derived::base
到Derived::*ptr
類型並且工作正常。
我想我應該記住的是,模板扣除不允許轉換。謝謝! –