Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ambiguous definition of operator() with multiple inheritance

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.

like image 487
mattia.penati Avatar asked Jan 28 '11 18:01

mattia.penati


People also ask

What is the ambiguity in multiple inheritance?

Inheritance Ambiguity in C++ In multiple inheritances, when one class is derived from two or more base classes then there may be a possibility that the base classes have functions with the same name, and the derived class may not have functions with that name as those of its base classes.

How can you solve the ambiguity that arises in multiple inheritance?

An ambiguity can arise when several paths exist to a class from the same base class. This means that a child class could have duplicate sets of members inherited from a single base class. This can be solved by using a virtual base class.

What is ambiguity problem in multiple inheritance in C++?

Ambiguity in Multiple Inheritance Suppose, two base classes have a same function which is not overridden in derived class. If you try to call the function using the object of the derived class, compiler shows error. It's because compiler doesn't know which function to call.

What is ambiguity inheritance in C++?

Ambiguity in inheritance can be defined as when one class is derived for two or more base classes then there are chances that the base classes have functions with the same name. So it will confuse derived class to choose from similar name functions.


1 Answers

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...

like image 139
peoro Avatar answered Oct 24 '22 20:10

peoro