C++ templates that accept only certain types

2019-01-01 03:29发布

In Java you can define generic class that accept only types that extends class of your choice, eg:

public class ObservableList<T extends List> {
  ...
}

This is done using "extends" keyword.

Is there some simple equivalent to this keyword in C++?

标签: c++ templates
13条回答
春风洒进眼中
2楼-- · 2019-01-01 04:04

I think all prior answers have lost sight of the forest for the trees.

Java generics are not the same as templates; they use type erasure, which is a dynamic technique, rather than compile time polymorphism, which is static technique. It should be obvious why these two very different tactics do not gel well.

Rather than attempt to use a compile time construct to simulate a run time one, let's look at what extends actually does: according to Stack Overflow and Wikipedia, extends is used to indicate subclassing.

C++ also supports subclassing.

You also show a container class, which is using type erasure in the form of a generic, and extends to perform a type check. In C++, you have to do the type erasure machinery yourself, which is simple: make a pointer to the superclass.

Let's wrap it into a typedef, to make it easier to use, rather than make a whole class, et voila:

typedef std::list<superclass*> subclasses_of_superclass_only_list;

For example:

class Shape { };
class Triangle : public Shape { };

typedef std::list<Shape*> only_shapes_list;
only_shapes_list shapes;

shapes.push_back(new Triangle()); // Works, triangle is kind of shape
shapes.push_back(new int(30)); // Error, int's are not shapes

Now, it seems List is an interface, representing a sort of collection. An interface in C++ would merely be an abstract class, that is, a class that implements nothing but pure virtual methods. Using this method, you could easily implement your java example in C++, without any Concepts or template specializations. It would also perform as slow as Java style generics due to the virtual table look ups, but this can often be an acceptable loss.

查看更多
登录 后发表回答