std::function template argument resolution

戏子无情 提交于 2019-11-29 04:19:04

I think what you can do is to create an intermediate return type deducing function which uses decltype to determine the arguments to be passed to the actual function object:

template <typename Out, typename In>
std::vector<Out> process_intern(std::vector<In> vals, std::function< Out(In) > func)
{
    // whatever
}

template <typename In, typename Func>
auto process(std::vector<In> vals, Func func) -> std::vector<decltype(func(vals[0]))>
{
    return process_intern<decltype(func(vals[0]))>(vals, func);
}

Of course, you may want to consider implementing the logic in process() directly anyway unless there is a reason to type erase the function type.

is there a way to get around this, so that I can deduce the input/return type of a callable object without explicitly mentioning them at the call site?

No. User-defined conversions are not considered in template argument deduction. The compiler have to come up with In and Out such that the type of the parameter and the type of the argument have to match (almost) exactly, but they never will in this case.

Perhaps parametrize the template on the function type instead of the input/return types

Yes, that's what is normally done (take a look at the standard library algorithms, for example)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!