C++ templates that accept only certain types

前端 未结 14 2381
一整个雨季
一整个雨季 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. :)

    0 讨论(0)
  • 2020-11-22 12:05

    An equivalent that only accepts types T derived from type List looks like

    template<typename T, 
             typename std::enable_if<std::is_base_of<List, T>::value>::type* = nullptr>
    class ObservableList
    {
        // ...
    };
    
    0 讨论(0)
提交回复
热议问题