vendredi 29 mai 2015

Static array of lambda functions (C++)

I'd like to do something like this (inside a class):

static constexpr MyStruct ops[6] = {
    {'+', [&] (double a, double b) { return a+b; } },
    {'-', [&] (double a, double b) { return a-b; } },
    ...
};

Being MyStruct like:

typedef double (*binOp)(double, double);
struct MyStruct {
    char c;
    binOp fn;
};

I also tried:

std::function <double(double,double)> fn;

for the definition of fn, but no luck.

The error I get for the first case is "error: field initializer is not constant" which I don't really get. If I try with std::function it's worse since it says "cannot be initialized by a non-constant expression when being declared".

Why is the lambda function non-constant? Am I missing something?

Thanks!

Aucun commentaire:

Enregistrer un commentaire