relaxxx
relaxxx

Reputation: 7824

template method overrides non-template method

I want to put any kind of Object (Object, Object etc.) into one shared_ptr. So I created base class and use shared_ptr.

But, how can I declare

T getMember();

within the base class so I can call ObjectBase.getMember?

class ObjectBase
{
public:
  //virtual getMember HOWTO?
};

template<typename T>
class Object : public ObjectBase
{
public:
  Object(T x):member(x) { }
  T getMember() { return member; }

private:
  T member;
};

Upvotes: 2

Views: 282

Answers (2)

That cannot be done. The compiler must know upfront how many different virtual functions (and overloads) will be available, but in your case you are considering adding new virtual member functions on demand based on new potential instantiations of the derived type.

In most cases, keeping completely unrelated objects in the same container is not a good design option, but for the few cases where it actually is, you can use variant types (consider boost::any or boost::variant, depending on your actual requirements. That is a bundled up, tested implementation of a variant type that you might be able to directly use.

Upvotes: 0

Xeo
Xeo

Reputation: 131779

You can't. How should such a declaration look, that it can return all kinds of types? It's just not possible. You'd have to cast the ObjectBase* to the correct Object<T>* and then use the getMember function. It's only possible if all T share a common base class, so you could return a pointer to that. But that would put a strict constraint on T.

Upvotes: 3

Related Questions