模板函数,它使用带有可变参数的lambda

时间:2017-11-13 04:32:28

标签: c++11 lambda template-function

教育任务:想要编写一个函数来获取功能对象及其参数,并使用完美转发来调用它:

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

语法有什么问题?怎么解决?

1 个答案:

答案 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)...);
}