C++ templates that accept only certain types

前端 未结 14 2647
一整个雨季
一整个雨季 2020-11-22 11:37

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

public class ObservableList {
  ...
         


        
14条回答
  •  甜味超标
    2020-11-22 11:59

    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 subclasses_of_superclass_only_list;

    For example:

    class Shape { };
    class Triangle : public Shape { };
    
    typedef std::list 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.

提交回复
热议问题