【问题标题】:C++: How to enforce the templated type to implement a certain operator(s)?C++:如何强制模板化类型来实现某个运算符?
【发布时间】:2022-01-14 23:02:39
【问题描述】:

有一个similar question 9 年前 (C++11),也许更新的标准提供了这个。

我想确保我正在编写的模板化类只有在使用的类型实现某些运算符时才能被实例化,例如<

template <typename T>
class XX {
private:
    T foo;
public:
    bool continiumTransfunctioneer(const T zoo){return zoo < foo;}
    // ...
};

我知道如果不满足该要求,代码将无法编译,但来自编译器的消息可能非常冗长——我希望能够预先警告用户。

【问题讨论】:

标签: c++ templates c++17 c++20 typetraits


【解决方案1】:

这是使用C++20 concepts 的一个很好的用例:

template <typename T>
  requires requires (const T& x, const T& y) { x < y; }
class XX {
 private:
  T foo;
 public:
  bool continiumTransfunctioneer(const T& zoo) const { return zoo < foo; }
};

Demo.

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-05
  • 2023-03-30
  • 2018-03-18
  • 2011-05-23
  • 1970-01-01
  • 1970-01-01
  • 2021-04-08
相关资源
最近更新 更多