教育任务:想要编写一个函数来获取功能对象及其参数,并使用完美转发来调用它:
auto fun = [](std::string a, std::string const& b) { return a += b; };
std::string s("world!");
s = apply(fun, std::string("Hello, "), s);
写了这个函数:
template<typename T, typename ... Args>
T apply(std::function<T(Args...)>&& fun, Args&& ... args)
{
return fun(std::forward<Args>(args)...);
}
然而得到错误:
error: no matching function for call to ‘apply(main()::<lambda(std::__cxx11::string, const string&)>&, std::__cxx11::string, std::__cxx11::string&)’
s = apply(fun, std::string("Hello, "), s);
^
candidate: template<class T, class ... Args> T&& apply(std::function<_Res(_ArgTypes ...)>, Args&& ...)
T apply(std::function<T(Args...)> fun, Args&& ... args)
^~~~~
note: template argument deduction/substitution failed:
note: ‘main()::<lambda(std::__cxx11::string, const string&)>’ is not derived from ‘std::function<_Res(_ArgTypes ...)>’
s = apply(fun, std::string("Hello, "), s);
语法有什么问题?怎么解决?
答案 0 :(得分:0)
没有std::function
的解决方案:
template<typename F, typename ... Args>
auto apply(F&& fun, Args&&... args) ->
decltype(std::forward<F>(fun)(std::forward<Args>(args)...))
{
return std::forward<F>(fun)(std::forward<Args>(args)...);
}