samedi 1 août 2015

C++11 std::function const overload ambiguity

I'm having a problem with a part of a larger program where something that I'd say is not ambiguous is considered ambiguous by both g++ and clang++

#include <functional>
#include <string>

struct Foo {
    Foo(int) {}
    Foo(std::string) {}
    operator int () const { return 42; }
    operator std::string () const { return ""; }

    void foo(std::function<void(Foo&, int)>f);
    void foo(std::function<void(const Foo&, int)>f) const; // xxx

    void foo(std::function<void(const std::string&, Foo&)>f);
    void foo(std::function<void(const std::string&, const Foo&)>f) const;

    void bar() const {
        this->foo([](const Foo&, int){}); // xxx
    }
};

I'd expect the invocation of ::foo made in bar to be unambiguously resolved to the const version marked with xxx, while instead both compilers complain that the overload resolution is ambiguous:

g++ -std=c++11 -c -Wall amb.cpp 
amb.cpp: In member function ‘void Foo::bar() const’:
amb.cpp:18:40: error: call of overloaded ‘foo(Foo::bar() const::<lambda(const Foo&, int)>)’ is ambiguous
         this->foo([](const Foo&, int){});
                                        ^
amb.cpp:12:10: note: candidate: void Foo::foo(std::function<void(const Foo&, int)>) const
     void foo(std::function<void(const Foo&, int)>f) const;
          ^
amb.cpp:15:10: note: candidate: void Foo::foo(std::function<void(const std::basic_string<char>&, const Foo&)>) const
     void foo(std::function<void(const std::string&, const Foo&)>f) const;
          ^

Why it's not clear which version I want to call? How can I work around this problem?

Aucun commentaire:

Enregistrer un commentaire