Suppose I want declare an inline function which will take an argument of arbitrary type. I think it can be done by the following ways.
//////
inline auto const myfunc = [&](const auto& val){return something(val);};
//////
inline auto myfunc(const auto& val)
{
return something(val);
}
//////
template<class T>
inline T myfunc(const T& val)
{
return something(val);
}
So I have several questions.
Thanks in advance.
They all 3 define something sightly different. Hence, answer to 2 is: Choose the one that does what you want. 1) I'll levave to you, because you can easily try them out to see if they compile. 3) isn't that relevant, because choosing between them is a matter of what you actually need, not of style.
inline auto const myfunc = [&](const auto& val){return something(val);};
The lambda myfunc
is of some unnamed type with a templated operator()
. myfunc
itself is not templated. You can pass myfunc
to other functions, because it is an object. You cannot do that easily with the other two.
The difference between
inline auto myfunc(const auto& val)
{
return something(val);
}
and
template<class T>
inline T myfunc(const T& val)
{
return something(val);
}
is the return type. With the second, the return type is T
. T
is either deduced from the paramter or you specify it explicitly and then it can be different from the parameter passed, as long as the parameter can convert to const T&
. Hence the first is more similar to the lambda (more precisely, to its operator()
), because the return type is deduced from something(val)
, though the lambda additionally captures via &
. You cannot do that easily with a function.