Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple concepts for template class

I have the class below, but it only works with floating points. How to add integers too? That is multiple requires statements? or is there something that can include all numerical types?

Or there is a better way?

#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
like image 283
DEKKER Avatar asked Dec 31 '22 11:12

DEKKER


2 Answers

You can || your concepts such as

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

you can also create a concept this way

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

then you can use this concept with your class

template <class T>
requires arithmetic<T>
class Complex
{
    ...
like image 117
Cory Kramer Avatar answered Jan 02 '23 01:01

Cory Kramer


There's already an std::is_arithmetic type trait that can be used with your requires clause:

#include <type_traits>

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

Note that if you go with a custom Arithmetic concept for this (I Imagine the standard library will provide one at some point but say you're impatient) it's clean(er) to write:

template <Arithmetic T>
class Complex
{
    ...
like image 32
Nikos Athanasiou Avatar answered Jan 02 '23 00:01

Nikos Athanasiou