gpt4 book ai didi

c++ - 如何传递方法并使用可变数量的参数调用它

转载 作者:行者123 更新时间:2023-12-04 08:23:00 25 4
gpt4 key购买 nike

我有课CallProtector这应该调用具有可变数量参数的方法,这些参数假设通过互斥锁保护调用,但我不知道如何使用它们的参数传递对象的方法。这是我到目前为止所拥有的:

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
感谢任何帮助,提前致谢。

最佳答案

以下可能对您有用:

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);

关于c++ - 如何传递方法并使用可变数量的参数调用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65406127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com