SU3
SU3

Reputation: 5409

Inheritance and template operator overloading

Inheritance and template operator overloading

I don't understand why the operator in A<int> overshadows the operator in base. It has a different signature after all.

#include <iostream>

struct base {
  template <typename U>
  void operator()(U&& x) { std::cout << "base" << std::endl; }
};

template <typename T>
struct A: public base { };

template <>
struct A<int>: public base {
  void operator()() { std::cout << "A<int>" << std::endl; } // line 1
};

int main()
{
  A<double>()(1);
  A<int>()(1); // line 2
  A<int>()();  // line 3
}

Line 2 does not compile if line 1 is present.

Line 3 does not compile if line 1 is removed (obviously).

If I copy the operator template from base to A, everything works.

I expected the output to be:

base
base
A<int>

Upvotes: 1

Views: 745

Answers (1)

skypjack
skypjack

Reputation: 50568

The declaration of the operator in the derived class hides the name in the base class.
To solve the issue, it's a matter of a using declaration:

template <>
struct A<int>: public base {
    using base::operator();
    void operator()() { std::cout << "A<int>" << std::endl; }
};

And both of them will compile.

Upvotes: 3

Related Questions