Search code examples
c++generic-programming

Using tags in function overloading


Why is method test in X ambiguous, and how can this be fixed?

struct A{};
struct B{};

template<typename T>
struct I { void test(T){} };
struct X : public I<A>, I<B> {};

int main(int argc, const char *argv[])
{
    X x;
    x.test(A());
    return 0;
}

Compile error:

In function ‘int main(int, const char**)’:
error: request for member ‘test’ is ambiguous
error: candidates are: void I<T>::test(T) [with T = B]
error:                 void I<T>::test(T) [with T = A]

Solution

  • test is ambiguous because it is a member of two base classes of X. While not both functions match, the name matches.

    Fix with an explicit forward:

    struct X : public I<A>, I<B> {
        template <typename T>
        void test(T t) { I<T>::test(t); }
    };