In java, to make a function that returns an object that is the same type as a parameter and extends a certain class, I would type:
Also wondered the same question, that's a C++20 approach through concepts.
#include
#include
#include
using namespace std;
class MyClass
{
public:
inline virtual void Print() const noexcept { cout << "Myclass" << endl; }
};
class Derived : public MyClass
{
public:
inline virtual void Print() const noexcept override { cout << "Derived" << endl; }
};
class NotDerived
{};
Create a concept with name CheckType which is satisfied when the concept's parameter Type is a BaseClass or a DerivedClass : BaseClass.
template
concept CheckType = std::is_base_of::value;
Create a generic class where the T type REQUIRES to be MyClass or Derived : MyClass type.
template
requires CheckType
class OnlyMyClass
{
private:
T Instance;
public:
inline void Print() const noexcept { Instance.Print(); } // Print
};
int main()
{
//OnlyMyClass O1; // error, the associated constraints are not satisfied.
OnlyMyClass O2; // nice!
OnlyMyClass O3; // nice!
O2.Print();
O3.Print();
return 0;
} // main