C++ templates that accept only certain types

前端 未结 14 2573
一整个雨季
一整个雨季 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 12:04

    There is no keyword for such type checks, but you can put some code in that will at least fail in an orderly fashion:

    (1) If you want a function template to only accept parameters of a certain base class X, assign it to a X reference in your function. (2) If you want to accept functions but not primitives or vice versa, or you want to filter classes in other ways, call a (empty) template helper function within your function that's only defined for the classes you want to accept.

    You can use (1) and (2) also in member functions of a class to force these type checks on the entire class.

    You can probably put it into some smart Macro to ease your pain. :)

提交回复
热议问题