Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bad function call when using a std::function as a comparator

I'm using lambdas instead of a comparator class for my set, but I'm running into issues.

I have something like this:

class Processor {
    
private:
    const function<bool(std::string, std::string)> _lenComp = [](string a, string b) { return a != b && a.size() >= b.size(); };
    set<string, decltype(_lenComp)> _inputSet;

// ...
    
public:
    Processor() : _inputSet() {
    }

    void addLine(string line) {
        _inputSet.insert(line);
    }
    

When I create a Processor instance and call addLine 2 times I get a bad function call exception. How do I properly initialize this class?

like image 764
user1402866 Avatar asked Oct 25 '25 14:10

user1402866


1 Answers

decltype(_lenComp) is function<bool(std::string, std::string)> which is an empty std::function, so you get bad call when calling it.

what you wanted was the type of the lambda stored in it, you should define that with static constexpr auto, because you are not allowed to know the type of the lambda.

class Processor {
    
private:
    static constexpr auto _lenComp = [](string a, string b) { return a != b && a.size() >= b.size(); };
    set<string, decltype(_lenComp)> _inputSet;
};
like image 159
Ahmed AEK Avatar answered Oct 27 '25 06:10

Ahmed AEK