自动协变类派生

时间:2013-10-29 23:20:46

标签: c++ templates inheritance c++11

拥有这样一个类的最佳方法是什么,

class Object
{
public:
    virtual Object* Find(string name);
};

实现,以便其派生类'Find()方法自动返回派生类类型,而不必执行以下操作:

class DerivedObject : public Object
{
public:
    DerivedObject* Find(string name);
};

手动?

额外:实际上在我的实际实现中,它是一堆static函数,而不是virtual个函数。我有static Object* Object::Find(string name)static GameObject* GameObject::Find(string name)等函数。

1 个答案:

答案 0 :(得分:2)

取消virtual函数,改写免费函数。

template<typename T>
T* Find(T& object, string name) {
}

您必须通过Find(derivedobject,name)而不是derivedobject.Find(name)来调用它,否则我认为这会按照您的喜好进行。

如果您需要访问friend数据,则还必须在Object内将其声明为protected。只需将以下行放在Object类中。

template<typename T>
friend
T* Find(T& object, string);
相关问题