我正在嘗試使用嵌套的std::invoke. 示例代碼:
class Executor
{
public:
bool Execute(bool someFlag);
};
template <class TMemberFunction, class TInstance, typename TResponse>
class Invoker
{
public:
TResponse Invoke(TMemberFunction* function, TInstance* instance, bool someFlag) {
return std::invoke(function, instance, someFlag);
}
};
void Main()
{
// Create an executor
Executor executor;
bool someFlag = true;
// How can I pass the member function type here?
Invoker<???, Executor, bool> invoker;
// Invoke member method
bool response = invoker.Invoke(&Executor::Execute, &executor, someFlag);
}
將成員函式的型別傳遞給Invoker模板的正確方法是什么?
編輯:示例代碼更正。
uj5u.com熱心網友回復:
你可以這樣寫你的Invoker類:
template <typename TMemberFunction>
class Invoker;
template <class C, typename Ret, typename... Args>
class Invoker<Ret (C::*) (Args...)>
{
public:
Ret Invoke(Ret (C::*method) (Args...), C* instance, Args... args) {
return std::invoke(method, instance, std::forward<Args>(args)...);
}
};
template <class C, typename Ret, typename... Args>
class Invoker<Ret (C::*) (Args...) const>
{
public:
Ret Invoke(Ret (C::*method) (Args...) const, const C* instance, Args... args) {
return std::invoke(method, instance, std::forward<Args>(args)...);
}
};
// other specializations to handle combination of volatile, ref, c-ellipsis
而不是使用它:
int main()
{
Executor executor;
Invoker <bool (Executor::*)(bool)> invoker;
bool response = invoker.Invoke(&Executor::Execute, &executor, true);
// ..
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/508186.html
