Non-local lambda expression cannot have a capture-default

  c++, lambda

I’m using lambda expressions to reduce else-if blocks when decoding a string into an operation- for instance, "sin" -> std::sin(x). I define a struct in the header file:

struct func{
    std::string symbol;
    uint8_t type;

    std::function<double (double, double)> operate;
};

Where symbol is the string that represents the function, and type is the number of inputs the function takes. In the cpp file, I initialize a func object as follows:
func f1{"sin", ONE_INPUT, [=] (double a, double b){return std::sin(a);}};

But when I compile the cpp file using g++ calc.cpp -o2 -std=c++17 -o calc.out, I get an error for the instantiation of each func object:
error: non-local lambda expression cannot have a capture-default

I’ve tried searching for this error online, but all I found was this discussion post where the solution says to make sure my g++ is version 7.4 or greater. However, my clang version is 12.0.0, so I doubt this is the issue.

Here is a MRE:

#define ONE_INPUT 0
#define TWO_INPUT 1

#include <iostream>
#include <cmath>
#include <math.h>
#include <string>
#include <cstdint>
#include <functional>

struct func{
    std::string symbol;
    uint8_t type;

    std::function<double (double, double)> operate;
};

int main(int argc, char** argv){
    func f1{"sin", ONE_INPUT, [=] (double a, double b){return std::sin(a);}};
    func f2{"cos", ONE_INPUT, [=] (double a, double b){return std::cos(a);}};
    func f3{"tan", ONE_INPUT, [=] (double a, double b){return std::tan(a);}};
}

Source: Windows Questions C++

LEAVE A COMMENT