Search code examples
c++templatesc++17inlinec++20

Inline Lambda variable vs Inline function vs Inline template function with automatic type deduction


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.

  1. Is there any error in my definitions, are these definitions supported?
  2. Does any of these definitions have any advantage over another, and if yes, what advantages?
  3. Which one of these definitions is better in terms of code quality?

Thanks in advance.


Solution

  • 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.