DEK*_*KER 4 c++ c++-concepts c++20
我有下面的课程,但它只适用于浮点。整数也如何相加?那是多个require语句吗?或者有什么可以包含所有数字类型的东西?
或者有更好的方法吗?
#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
Run Code Online (Sandbox Code Playgroud)
你可以||你的概念,例如
requires std::floating_point<T> || std::integral<T>
Run Code Online (Sandbox Code Playgroud)
你也可以用这种方式创建一个概念
template <typename T>
concept arithmetic = std::integral<T> || std::floating_point<T>;
Run Code Online (Sandbox Code Playgroud)
那么你可以在你的课堂上使用这个概念
template <class T>
requires arithmetic<T>
class Complex
{
...
Run Code Online (Sandbox Code Playgroud)