flexter
flexter

Reputation: 117

Declaring lambda function with auto in a C++ class

Is it possible to declare a lambda function in a C++ class with auto? I am getting a compilation error:

error: in-class initializer for static data member of type 'const Temp::(lambda at a.cpp:8:29)' requires 'constexpr' specifier

I am defining a custom sort function for a set which is a class member variable, and I want to define this sort function within the class. How can I fix this?

Secondly, even if I move the lambda function line outside of the class, I am getting an error at the line where I declare the set:

error: unknown type name 'cmp'

Why and how can I fix it?

class Temp {
public:
    static const auto cmp = [](int p1, int p2)
        {
            return p1>p2;
        };
    set<int, decltype(cmp) > sortedSet(cmp);
    Temp() {
    }
}

Upvotes: 1

Views: 295

Answers (1)

apple apple
apple apple

Reputation: 10591

  • use constexpr as as compiler suggest
  • std::set<int, decltype(cmp)> sortedSet(cmp) is parse as function
    • like int sortedSet(int);
#include <set>
class Temp {
public:
    static constexpr auto cmp = [](int p1, int p2)  // <-- use constexpr
        {
            return p1>p2;
        };
    std::set<int, decltype(cmp) > sortedSet{cmp}; // <-- use uniform initialization
    Temp() {
    }
};

alternatively you can also do it with normal function

#include <set>
class Temp {
public:
    static bool cmp(int p1, int p2) {
        return p1>p2;
    };
    std::set<int, decltype(&cmp) > sortedSet{cmp};
    Temp() {
    }
};

Upvotes: 2

Related Questions