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)
Since I can't comment on the accepted answer, I'm providing a new answer which builds on it.

The template parameters can be simplified by having the `enable_if` condition become the [default type template parameter](http://en.cppreference.com/w/cpp/language/template_parameters#Type_template_parameter) instead of `nullptr`.

```
template<typename T, typename = std::enable_if<std::is_base_of<MyClass, T>::value>>

```