Ambiguous definition of operator() with multiple inheritance

孤者浪人 提交于 2020-01-11 08:23:05

问题


I compile this code with GCC (4.2.1 Apple build 5664)

#include <cstddef>

using std::size_t;

template <char I> struct index { };

struct a
{
    void operator()(size_t const &) { }
};

struct b
{
    template <char I>
    void operator()(index<I> const &) { }
};

struct c: public a, public b { };

int main (int argc, char const *argv[])
{
    c vc;
    vc(1);

    return 0;
}

and give me the following error:

main.cpp: In function ‘int main(int, const char**)’:
main.cpp:22: error: request for member ‘operator()’ is ambiguous
main.cpp:14: error: candidates are: template<char I> void b::operator()(const index<I>&)
main.cpp:9:  error:                 void a::operator()(const size_t&)

I don't understand the reason why this code is ambiguous; the two methods have different signatures.


回答1:


Modify c this way:

struct c: public a, public b
{
    using a::operator();
    using b::operator();
};

C++ (prior to C++0x) is kind of awkward in inheriting functions: if you provide a function with the same name of a base class' function it hides base class ones.

It looks like also inheriting from two classes has the same problem.

// looking for the standard...




回答2:


Name resolution is done before overload resolution.
There is no operator() in c so the compiler goes looking for operator() in it's base classes and finds one in a and another in b making the name ambiguous (and no overload resolution takes place).

If you want to eliminate the name ambiguity you can call a::operator() explicitly: vc.a::operator()(1);




回答3:


Its ambiguous because you are passing in an integer constant that can (presumably) be casted to either a std::size_t or index types. Change main to the following and it should resolve it:

int main (int argc, char const *argv[])
{
    c vc;
    vc(static_cast<std::size_t>(1));

    return 0;
}

With that said, it is highly likely that you shouldn't be using multiple inheritance here.



来源:https://stackoverflow.com/questions/4831759/ambiguous-definition-of-operator-with-multiple-inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!