[英]How to pass method and call it with variable number of arguments
我有 class CallProtector
,它應該調用可變編號為 arguments 的方法,它應該通過互斥鎖保護調用,但我無法弄清楚如何使用它們的 arguments 傳遞對象的方法。這是我到目前為止所擁有的:
class CallProtector
{
public:
template<typename F, typename ...Args>
void callProtectedMethod(F& lambda, Args... args)
{
std::lock_guard<std::mutex> guard(m_guard);
lambda(args);
}
private:
std::mutex m_guard;
};
我正在嘗試以這種方式使用它:
class Car
{
public:
void updateEngine(int engineModelType) {}
};
int main()
{
Car alfaRomeo;
CallProtector callProtector;
callProtector.callProtectedMethod(&Car::updateEngine, 10);
return 0;
}
但是我有編譯錯誤說
no instance of function template "CallProtector::callProtectedMethod" matches the argument list
感謝任何幫助,在此先感謝。
由於 C++17 您可以使用std::invoke
,只需將所有 arguments 轉發給它:
template<typename ...Args>
void callProtectedMethod(Args&&... args)
{
std::lock_guard<std::mutex> guard(m_guard);
std::invoke(std::forward<Args>(args)...);
}
此外,如果您想在 Car 實例上調用成員 function,則必須將指針傳遞給 object。
以下可能對您有用:
class CallProtector
{
public:
template<typename F, typename ...Args>
void callProtectedMethod(F&& func, Args&&... args)
{
std::lock_guard<std::mutex> guard(m_guard);
func(std::forward<Args>(args)...);
}
private:
std::mutex m_guard;
};
然后像這樣使用它:
Car alfaRomeo;
CallProtector callProtector;
auto updateEngine = std::bind(&Car::updateEngine, &alfaRomeo, std::placeholders::_1);
callProtector.callProtectedMethod(updateEngine, 10);
編輯
或者這也行得通:
template<typename F, typename ...Args>
void callProtectedMethod(F&& func, Args&&... args)
{
std::lock_guard<std::mutex> guard(m_guard);
std::invoke(std::forward<F>(func), std::forward<Args>(args)...);
}
接着
callProtector.callProtectedMethod(&Car::updateEngine, alfaRomeo, 10);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.