简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM