【问题标题】:multiple concepts for template class模板类的多个概念
【发布时间】:2021-12-28 20:14:02
【问题描述】:

我有下面的课程,但它只适用于浮点数。如何也添加整数?那是多个需要语句?或者有什么可以包含所有数字类型的东西?

或者有更好的方法吗?

#ifndef COMPLEX_H
#define COMPLEX_H

#include <concepts>
#include <iostream>

template <class T>
requires std::floating_point<T> // How to add integral, signed integral, etc
class Complex {
private:
    T re = 0;
    T im = 0;

public:
    Complex() {
        std::cout << "Complex: Default constructor" << std::endl;
    };

    Complex(T real) : re{re} {
        std::cout << "Complex: Constructing from assignement!" << std::endl;
    };

    bool operator<(const Complex<T>& other) {
        return re < other.re && im < other.im;
    }
};

#endif // COMPLEX_H

【问题讨论】:

    标签: c++ c++20 c++-concepts


    【解决方案1】:

    你可以||你的概念比如

    requires std::floating_point<T> || std::integral<T> 
    

    您也可以通过这种方式创建概念

    template <typename T>
    concept arithmetic = std::integral<T> || std::floating_point<T>;
    

    那么你可以在你的类中使用这个概念

    template <class T>
    requires arithmetic<T>
    class Complex
    {
        ...
    

    【讨论】:

      【解决方案2】:

      已经有一个 std::is_arithmetic 类型特征可以与您的 requires 子句一起使用:

      #include <type_traits>
      
      template <class T>
      requires std::is_arithmetic_v<T>
      class Complex
      {
         ...
      

      请注意,如果您为此使用自定义 Arithmetic 概念(我想象标准库会在某个时候提供一个但说您不耐烦),那么编写起来很干净(呃):

      template <Arithmetic T>
      class Complex
      {
          ...
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-21
        • 2020-05-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多