Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot initialize a lambda member variable a default argument

I would like to compile the code below with c++17, so that I can pass any function (lambda) that has a specific signature, int(int), while also allowing the default argument:

template <class F = int(int)> // for deduction
struct A{
        A(F f = [] (int x){return x;}) : f_{f} {}

        F f_;
};

int main() {
        A work([](int x){return x + 1;});
        A not_work; // compile error.
}

However, clang emits an error:

a.cpp:6:4: error: data member instantiated with function type 'int (int)'
        F f_;
          ^
a.cpp:11:4: note: in instantiation of template class 'A<int (int)>' requested here
        A not_work;
          ^

I don’t understand why the member f_ can be initialized when I pass the lambda and the default lambda argument cannot be?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Meanwhile, is there any better way to do this?

>Solution :

As the error message said, can’t declare a data member with a function type like int(int).

You might use a function pointer type (lambdas without capture could convert to function pointer implicitly) or std::function<int(int)>. E.g.

template <class F = int(*)(int)> // for deduction
struct A{
        A(F f = [] (int x){return x;}) : f_{f} {}

        F f_;
};

Or

template <class F = std::function<int(int)>> // for deduction
struct A{
        A(F f = [] (int x){return x;}) : f_{f} {}

        F f_;
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading