I am currently working on a library where I am chaining function objects.
I am creating a function template that takes a callable object (std::function at the moment) and is parametrized on the output and input type of the function. Here is a simplified version of what I am defining:
template <typename In, typename Out>
std::vector<Out> process(std::vector<In> vals, std::function< Out(In) > func)
{
// apply func for each value in vals
return result;
}
The problem I am having is on usage. It seems that when I pass a lambda, the compiler cannot deduce the type correctly, so complains that the function doesn't exist:
std::vector<string> strings;
// does NOT compile
auto chars = process(strings,
[]( std::string s ) -> char
{
return s[0]; // return first char
}
);
If I explicitly wrap the lambda in std::function
, the program compiles:
std::vector<string> strings;
// DOES compile
auto chars = process(strings,
std::function< char(std::string) >(
[]( std::string s ) -> char
{
return s[0]; // return first char
})
);
I haven't tested passing function pointers or function objects yet, but it seems like it will be difficult for the compiler to deduce the the In
and Out
parameters if I'm not directly passing the explicit std::function
object.
My question is this: 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?
Perhaps parametrize the template on the function type instead of the input/return types? Essentially I need to deduce the In
and Out
type for an arbitrary callable. Perhaps some kind of auto
/decltype
trick for the return type of the template function?
Thank you.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…