C++ templates that accept only certain types

前端 未结 14 2628
一整个雨季
一整个雨季 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:47

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

    No.

    Depending on what you're trying to accomplish, there might be adequate (or even better) substitutes.

    I've looked through some STL code (on linux, I think it's the one deriving from SGI's implementation). It has "concept assertions"; for instance, if you require a type which understands *x and ++x, the concept assertion would contain that code in a do-nothing function (or something similar). It does require some overhead, so it might be smart to put it in a macro whose definition depends on #ifdef debug.

    If the subclass relationship is really what you want to know about, you could assert in the constructor that T instanceof list (except it's "spelled" differently in C++). That way, you can test your way out of the compiler not being able to check it for you.

提交回复
热议问题