0

I am playing with the Curiously Recurring Template Pattern and call operator overload and I am facing a compilation error I can't explain. I defined the following classes:

template<class DERIVED>
struct Base
{
    void operator() (int n) const {}
    void foo        (int n) const {}
};

struct Derived : Base<Derived>
{
    void operator() (int n, int m) const {}
};

int main()
{
    Derived  x;
    
    x (1,2);                            // ok
    x (1);                              // ko -> does not compile
    static_cast<Base<Derived>>(x) (1);  // ok
    x.foo(1);                           // ok
}

I can instantiate x and the compiler is happy with the operator defined in Derived but not with the one defined in Base; I have to force a static_cast on the Base class in order to make the one arg operator work. On the other hand, there is no issue when calling foo.

Why the one arg overload is not directly usable on a Derived instance ?

edrezen
  • 127
  • 1
  • 7
  • 1
    you can't overload a function from a base class, any overloads hide the base class function: https://godbolt.org/z/x9TG96h3r – Alan Birtles Apr 03 '23 at 13:12

1 Answers1

2

operator() in Derived is hiding the operator in the base class. If you want to be able to call the base class operator(), bring it into Derived with using:

struct Derived : Base<Derived>
{
    using Base<Derived>::operator();

Demo

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108