-1

In C++ I can write:

auto sum(const auto& x1, const auto& x2)
{
    return x1 + x2;
}

int main()
{
    cout << sum(1, 2) << endl;
    cout << sum(1, 2.3) << endl;
    cout << sum(1.4, 2.3) << endl;
}

Which outputs: 3 3.3 3.7

To write same code with templates:

template<class X1, class X2> auto sum1(const X1& x1, const X2& x2)
{
    return x1 + x2;
}

looks more complex. Does this mean lambdas can replace function templates?

max66
  • 65,235
  • 10
  • 71
  • 111
Andrey Rubliov
  • 1,359
  • 2
  • 17
  • 24

3 Answers3

4

auto sum(const auto& x1, const auto& x2) is not a lambda. It is in fact an abbreviated function template, which should answer your question. It doesn't replace function templates: it's the same thing, only using a shorthand.

Casey
  • 41,449
  • 7
  • 95
  • 125
Nelfeal
  • 12,593
  • 1
  • 20
  • 39
4

Uhmmm...

1) the following code isn't legal C++ code, at the moment; maybe in future (C++20?) but not until C++17

auto sum(const auto& x1, const auto& x2)
{
    return x1 + x2;
}

2) it's a valid code (but only from C++14) your template code

template<class X1, class X2> auto sum1(const X1& x1, const X2& x2)  
{
    return x1 + x2;
}

3) a valid alternative is a generic-lambda (also from C++14)

[](auto const & x1, auto const & x2){ return x1+x2; }

4) in C++11 you can't use simply auto for return type but you have to explicit it with a trailing return type; by example, with decltype() in the following code

template<class X1, class X2>
auto sum1 (X1 const & x1, X2 const & x2)
   -> decltype( x1+x2 )
{ return x1 + x2; }

or also without auto

template<class X1, class X2>
decltype( std::declval<X1 const>() + std::declval<X2 const>() )
      sum1 (X1 const & x1, X2 const & x2)
 { return x1 + x2; }

5) a generic-lambda can (roughly) replace a function template but, starting from C++20, a lambda function could be (probably) a template one itself with a syntax as follows

[]<typename X1, typename X2>(X1 const & x1, X2 const &x2){ return x1+x2) }  
max66
  • 65,235
  • 10
  • 71
  • 111
0

your first code is not a lambda function.

and you cannot say that lambda can replace template functions

You can use lambda to write functions definition and you can define it anywhere in your code , we usually use it if you are sure that you will use it only once.

BTW , auto as not a good way to be able to use more than one datatype , it can cause some problems and does not work with all c++ versions.

  • 4
    "lambda is just anther way to write function definition" NO! lambda is writing a class which has a callable operator and create an instance in place. That is a bit different from writing a function... – Klaus Jan 07 '19 at 18:15