Yes, C ++ supports this. It was called covariant return types. You just need to declare a virtual function and declare return types accordingly. That is all that is needed.
struct base {
virtual base *foo() {
}
};
struct derived : public base {
virtual derived *foo() {
}
};
derived d;
base *base_ptr = d.foo();
:
- , , .
.
, , , , , .
, ; . .
#define FOO(T) virtual T *foo() { return new T; }
struct base {
FOO(base)
virtual ~base() {}
};
struct derived : public base {
FOO(derived)
};
, :
template <class T>
T *ComplicatedFunctionReturningT()
{
T *t;
return t;
}
struct base {
virtual base *foo() {
return ComplicatedFunctionReturningT<base>();
}
virtual ~base() {}
};
struct derived : public base {
virtual derived *foo() {
return ComplicatedFunctionReturningT<derived>();
}
};
, .
- . , :
class base {
public:
base *foo() {
base *ptr = fooImpl();
return ptr;
}
virtual ~base() {}
private:
virtual base *fooImpl() = 0;
};
class derived1 : public base {
private:
virtual derived1 *fooImpl() {
return new derived1;
}
};
class derived2 : public base {
private:
virtual derived2 *fooImpl() {
return new derived2;
}
};
, , . ++ - script.
, , , . , , , , .