Home >Backend Development >C++ >Why Does My Recursive Lambda Function Fail to Compile, and How Can I Fix It?

Why Does My Recursive Lambda Function Fail to Compile, and How Can I Fix It?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-13 13:46:11874browse

Why Does My Recursive Lambda Function Fail to Compile, and How Can I Fix It?

Resolving Compilation Issues with Recursive Lambda Functions

In attempting to define a recursive lambda function, the following code fails to compile:

auto sum = [term,next,&sum](int a, int b)mutable ->int {
  if(a>b)
    return 0;
  else
    return term(a) + sum(next(a),b);
};

The error stems from the inability to use "auto" when initializing a lambda function that captures itself. Auto type inference cannot determine the return type of the lambda, as it depends on its captured variables.

To rectify this issue, the following steps can be taken:

  1. Use a Fully Specified Function Object Type:

    std::function<int(int,int)> sum = [term,next,&amp;sum](int a, int b)->int {
      if(a>b)
        return 0;
      else
        return term(a) + sum(next(a),b);
    };

    Specifying the function object type eliminates the need for auto type inference, allowing the compiler to determine the return type accurately.

  2. Initialize the Function Object Later:

    std::function<int(int, int)> sum;
    
    sum = [term, next, &amp;sum](int a, int b) -> int {
        if (a > b)
            return 0;
        else
            return term(a) + sum(next(a), b);
    };

    Initializing the function object without an initial value allows the compiler to infer its type in the assignment statement.

The above is the detailed content of Why Does My Recursive Lambda Function Fail to Compile, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn