C++ 如何传递方法并使用可变数量的参数调用它
我有一个类C++ 如何传递方法并使用可变数量的参数调用它,c++,c++14,c++17,variadic-templates,variadic-functions,C++,C++14,C++17,Variadic Templates,Variadic Functions,我有一个类CallProtector,它应该调用具有可变数量的参数的方法,这些参数应该通过互斥来保护调用,但我不知道如何通过它们的参数传递对象的方法。以下是我迄今为止的情况: class CallProtector { public: template<typename F, typename ...Args> void callProtectedMethod(F& lambda, Args... args) { std::lock_
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;
};
但我有一个错误的说法
no instance of function template "CallProtector::callProtectedMethod" matches the argument list
感谢您的帮助,提前感谢。由于C++17,您可以使用
std::invoke
,只需将所有参数转发给它即可:
template<typename ...Args>
void callProtectedMethod(Args&&... args)
{
std::lock_guard<std::mutex> guard(m_guard);
std::invoke(std::forward<Args>(args)...);
}
模板
void callProtectedMethod(Args&&…Args)
{
std::锁紧护罩(m护罩);
std::invoke(std::forward以下内容可能适合您:
class CallProtector
{
公众:
模板
void callProtectedMethod(F&&func,Args&&…Args)
{
std::锁紧护罩(m护罩);
func(std::forward(args)…);
}
私人:
std::互斥mu-guard;
};
然后像这样使用它:
caralfaromeo;
CallProtector CallProtector;
自动更新引擎=std::bind(&Car::updateEngine,&alfaRomeo,std::占位符::_1);
callProtector.callProtectedMethod(更新引擎,10);
编辑
或者这也行:
模板
void callProtectedMethod(F&&func,Args&&…Args)
{
std::锁紧护罩(m护罩);
调用(std::forward(func)、std::forward(args)…);
}
然后
callProtector.callProtectedMethod(&Car::updateEngine,alfaRomeo,10);
<代码> >谢谢,但它对我来说不适用。编译错误说:“调用没有匹配的重载函数。我正在使用Visual Studio 2019与C++ 17。我们也可以用C++ 14来做同样的事情吗?@奥列格为什么不让<代码> CalpReCeCudiod方法< /代码>作为函数接受任何可调用的对象?std::bind
函数的结果-传递参数没有问题,只需调用具有互斥保护的函数即可。我必须使用不同的对象并传递指向它的指针。它对我不起作用,它说:“term不会对接受1个参数的函数求值”。但我们不能将所有参数转发给std::invoke?是吗不管出于什么原因?它应该很简单,但我真的不明白。什么术语
?我想你没有向我们展示所有的代码。它可以工作,这是msvc谢谢,是的,我的错误,这段代码可以工作。但是我们可以避免绑定和转发所有参数吗?我使用这段代码使它实际工作:std::invoke(std::forward(func),std::forward(args);
template<typename ...Args>
void callProtectedMethod(Args&&... args)
{
std::lock_guard<std::mutex> guard(m_guard);
std::invoke(std::forward<Args>(args)...);
}