Forced overload of a static method in a child class in C ++

I have something like this:

class Base
{
  public:
    static int Lolz()
    {
      return 0;
    }
};

class Child : public Base
{
  public:
    int nothing;
};

template <typename T>
int Produce()
{
  return T::Lolz();
}

and

Produce<Base>();
Produce<Child>();

both return 0, which, of course, is correct, but undesirable. Is there anyway to use an explicit declaration of the Lolz () method in the second class, or perhaps throw a compile-time error when using Produce<Child>()?

Or is it a bad OO design, and I have to do something completely different?

EDIT:

What I'm basically trying to do is to do something like this work:

Manager manager;

manager.RegisterProducer(&Woot::Produce, "Woot");
manager.RegisterProducer(&Goop::Produce, "Goop");

Object obj = manager.Produce("Woot");

or, in a more general sense, an external abstract factory that does not know the types of objects being created, so that new types can be added without writing more code.

+3
4

. , , .

(1) Produce() .

template <typename T>
int Produce()
{
  return T::Lolz();
}
class Base
{
    friend int Produce<Base>();

protected:
    static int Lolz()
    {
        return 0;
    }
};

class Child : public Base
{
public:
    int nothing;
};

int main(void)
{
    Produce<Base>(); // Ok.
    Produce<Child>(); // error :'Base::Lolz' : cannot access protected member declared in class 'Base'
}

(2) .

template <typename T>
int Produce()
{
  return T::Lolz();
}
class Base
{
public:
    static int Lolz()
    {
        return 0;
    }
};

class Child : public Base
{
public:
    int nothing;
};

template<>
int Produce<Child>()
{
    throw std::bad_exception("oops!");
    return 0;
}

int main(void)
{
    Produce<Base>(); // Ok.
    Produce<Child>(); // it will throw an exception!
}
+6

, . , . , Lolz() .

, . - . , B A, B, A.

+2

++ . , vtable, , , .

+1

, . - :


class Child : public Base
{
public:
    int nothing;
private:
    using Base::Lolz;
};

Child::Lolz . , , :)

0

Source: https://habr.com/ru/post/1709883/


All Articles