采用带有可变参数的 lambda 的模板函数
Template function which takes lambda with variadic parameters
教育任务:想要编写一个接受函数对象及其参数并使用完美转发调用它的函数:
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);
语法有什么问题?如何解决?
没有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)...);
}
教育任务:想要编写一个接受函数对象及其参数并使用完美转发调用它的函数:
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);
语法有什么问题?如何解决?
没有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)...);
}