Skip to content

File subtract.h

File List > algebra > operators > subtract.h

Go to the documentation of this file

#ifndef TEMPLAT_LATTICE_ALGEBRA_SUBTRACT_H
#define TEMPLAT_LATTICE_ALGEBRA_SUBTRACT_H

/* This file is part of TempLat, available at https://cosmolattice.github.io/templat .
   Copyright 2021-2026 The TempLat authors, see AUTHORS.md.
   Released under the MIT license, see LICENSE.md. */

// File info: Main contributor(s): Wessel Valkenburg, Franz R. Sattler, Year: 2025

#include "TempLat/lattice/algebra/constants/halftype.h"
#include "TempLat/lattice/algebra/operators/binaryoperator.h"
#include "TempLat/lattice/algebra/operators/unaryminus.h"
#include "TempLat/lattice/algebra/helpers/isarithmetic.h"

namespace TempLat
{
  namespace Operators
  {
    template <typename R, typename T> class Subtraction : public BinaryOperator<R, T>
    {
    public:
      using BinaryOperator<R, T>::mR;
      using BinaryOperator<R, T>::mT;

      Subtraction(const R &pR, const T &pT) : BinaryOperator<R, T>(pR, pT) {}

      template <typename... IDX>
        requires requires(std::decay_t<R> r, std::decay_t<T> t, IDX... idx) {
          requires IsVariadicIndex<IDX...>;
          DoEval::eval(r, idx...);
          DoEval::eval(t, idx...);
        }
      DEVICE_INLINE_FUNCTION auto eval(const IDX &...idx) const
      {
        return DoEval::eval(mR, idx...) - DoEval::eval(mT, idx...);
      }

      virtual std::string operatorString() const override { return "-"; }

      template <typename U> auto d(const U &other) { return GetDeriv::get(mR, other) - GetDeriv::get(mT, other); }
    };
  } // namespace Operators

  template <typename R, typename T>
    requires ConditionalBinaryGetter<R, T>
  Operators::Subtraction<R, T> operator-(const R &r, const T &t)
  {
    return Operators::Subtraction<R, T>(r, t);
  }

  template <typename T> T &operator-(T &&a, ZeroType b) { return a; }

  template <typename T>
    requires(!std::is_same_v<T, ZeroType>)
  auto operator-(ZeroType a, const T &b)
  {
    return Operators::UnaryMinus<T>(b);
  }

  template <typename T, typename S> auto operator-(T &&a, Operators::UnaryMinus<S> &&b)
  {
    return a + (-b); /* let the double-unary-minus detection take care of peeling b out if it */
  }

  constexpr inline HalfType operator-(const OneType a, const HalfType b) { return b; }

  inline auto operator-(HalfType a, OneType b) { return Operators::UnaryMinus<HalfType>(a); }

  constexpr inline auto operator-(OneType a, OneType b) { return ZeroType(); }
} // namespace TempLat

#endif