简体   繁体   中英

How to do a compile time type_check and only compile parts of my class if my class members' type matches the types?

template<class T = int>
struct v2 {
  T x;
  // this is the part
  template<class T, std::enable_if?>
  v2& operator++(int n) {}
};

I would like to enable it so ++v2 only compiles when it's an integer (or a long), and doesn't if it's anything else.

You need to partially specialize v2 :

template<class T = int, typename = void>
struct v2 {
  T x;
};

template<class T>
struct v2<T, std::enable_if_t<std::is_same_v<T, int> || std::is_same_v<T, long>>> {
  T x;
  v2& operator++(int);
};

Alternatively, common functionality can be put in another class used as base of v2 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM