N. Virgo
N. Virgo

Reputation: 8439

Why can't I use a lambda as a comparator for a set defined in a class?

This is fairly standard and works fine:

#include <set>

auto cmp = [](int a, int b) { return a > b; };
using stype = std::set<int, decltype(cmp)>;

stype mySet(cmp);

But why can't I do this?

#include <set>

auto cmp = [](int a, int b) { return a > b; };
using stype = std::set<int, decltype(cmp)>;

struct foo {
    stype mySet(cmp);
};

This fails with Unknown type name 'cmp' (in XCode 5.1.1, compiling for Mac using llvm, in case it's relevant.)

What is the reason for this error, and how can I fix / work around it? Do I have to avoid using a lambda for this purpose, and if so, why?

My actual code has several classes that store objects of type stype::iterator to point to items inside foo::mySet, so I do want to declare stype outside the struct.

Upvotes: 2

Views: 254

Answers (1)

Brian Bi
Brian Bi

Reputation: 119099

A non-static data member initializer must be a brace-or-equal-initializer. The following should work:

stype mySet {cmp};
stype mySet = stype(cmp);

However, stype mySet(cmp); is parsed as declaring a member function named mySet that returns stype and takes an unnamed argument of type cmp, hence the error.

Upvotes: 4

Related Questions