Home > Enterprise >  multiple concepts for template class
multiple concepts for template class

Time:12-29

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

CodePudding user response:

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
{
    ...

CodePudding user response:

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
{
    ...
  • Related