Question: 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:

```java
public <T extends MyClass> T foo(T bar) {...}

```

Is there a C++ equivalent of this?

In other words, how do I make a function that takes any class that extends a certain class, and returns that same type? (This is for the purpose of abstract/pure virtual classes).

Answer: 
We can use `enable_if` here if you have C++11 or higher available to you

```
template<typename T, typename std::enable_if<std::is_base_of<MyClass, T>::value>::type* = nullptr>
T Foo(T bar)
{
    return T();
}

```

For example:

```
class MyClass
{
public:
    int a = 1;
};

class Derived : public MyClass
{
public:
    int b = 2;
};

class NotDerived
{
public:
    int b = 3;
};

template<typename T, typename std::enable_if<std::is_base_of<MyClass, T>::value>::type* = nullptr>
T Foo(T bar)
{
    return T();
}

int main()
{
    Derived d;
    NotDerived nd;
    std::cout << Foo(d).b << std::endl;; // works
    //std::cout << (Foo(nd)).b << std::endl;; //compiler error

    return 0;
}

```

[Live Demo](http://ideone.com/rkFVXa)
Also wondered the same question, that's a C++20 approach through concepts.

```
#include <iostream>
#include <utility>
#include <concepts>
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 <class Type, class BaseClass>
concept CheckType = std::is_base_of<BaseClass, Type>::value;

```

Create a generic class where the T type REQUIRES to be MyClass or Derived : MyClass type.

```
template <class T>
requires CheckType<T, MyClass>
class OnlyMyClass
{
    private:
        T instance;

    public:
        inline void print() const noexcept { instance.print(); }    // Print
};  

int main()
{
    //OnlyMyClass<NotDerived> o1; // error, the associated constraints are not satisfied.
    OnlyMyClass<MyClass>    o2; // nice!
    OnlyMyClass<Derived>    o3; // nice!
    o2.print();
    o3.print();

    return 0;
}   // main

```