我正在尝试找到一种方法来调用多个类成员函数,每个函数都有不同的参数,并且在调用前后会发生某些已知功能。
这个包装函数是我试过的,但是例如对它的最终调用不会编译错误:
'bool Wrapper(Work * ,std::function< bool(Args...)>,Args &&...)' : could not deduce template argument for 'std::function< bool(double,std::string,Args...)>' from 'std::_Bind< true,bool,std::_Pmf_wrap< bool (__thiscall Work::* )(double,std::string),bool,Work,double,std::string>,Work *const >'
class Work
{
public:
void DoWork(int a, double b, string c);
private:
void Pre() {};
void Post() {};
bool Step1() { return true; }
bool Step2(int) { return true; }
bool Step3(double, string) { return true; }
};
template<typename... Args>
bool Wrapper(Work *work, std::function<bool(Args...)> func, Args&&... args)
{
work->Pre();
bool ret = func(std::forward<Args>(args)...);
work->Post();
return ret;
}
void Work::DoWork(int a, double b, string c)
{
if (!Wrapper<>(this, std::bind(&Work::Step1, this))) // error
return;
if (!Wrapper<int>(this, std::bind(&Work::Step2, this), a)) // error
return;
if (!Wrapper<double, string>(this, std::bind(&Work::Step3, this), b, c)) // error
return;
}
int main()
{
Work work;
work.DoWork(1, 2.0, "three");
return 0;
}
(将前置和后置功能放在步骤中乍一看似乎更可取,但这是不可取的,因为上面是实际代码的一个粗略简化的示例,并且步骤有多个返回位置,并且没有测试.)
我认为显式模板参数将使模板解析成为可能。我做错了什么?
最佳答案
在 C++11 中,std::bind
可以被 lambda 替换,您可以移除包装器的模板:
class Work
{
public:
void DoWork(int a, double b, string c);
private:
void Pre() {};
void Post() {};
bool Step1() { return true; }
bool Step2(int) { return true; }
bool Step3(double, string) { return true; }
friend bool Wrapper(Work *work, std::function<bool()> func);
};
bool Wrapper(Work *work, std::function<bool()> func)
{
work->Pre();
bool ret = func();
work->Post();
return ret;
}
void Work::DoWork(int a, double b, string c)
{
if (!Wrapper(this, [this]() -> bool { return this->Step1(); }))
return;
if (!Wrapper(this, [this, a]() -> bool { return this->Step2(a); }))
return;
if (!Wrapper(this, [this, b, c]() -> bool { return this->Step3(b, c); }))
return;
}
int main()
{
Work work;
work.DoWork(1, 2.0, "three");
return 0;
}
关于c++ - 无法从 std::bind 推断出 std::function 的模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37179591/