最終更新日時(UTC):
が更新

履歴 編集

function template
<valarray>

std::operator&

namespace std {
  template <class T>
  ValOrProxy<T> operator&(const ValOrProxy<T>& xs,
                          const ValOrProxy<T>& ys);                     // (1)

  template <class T>
  ValOrProxy<T> operator&(const ValOrProxy<T>& xs,
                          const T& y);                                  // (2) C++17 まで
  template <class T>
  ValOrProxy<T> operator&(const ValOrProxy<T>& xs,
                          const typename valarray<T>::value_type& y);   // (2) C++20 から

  template <class T>
  ValOrProxy<T> operator&(const T& x,
                          const ValOrProxy<T>& ys);                     // (3) C++17 まで
  template <class T>
  ValOrProxy<T> operator&(const typename valarray<T>::value_type& x,
                          const ValOrProxy<T>& ys);                     // (3) C++20 から
}

概要

valarrayにおいて、左辺と右辺の論理積を得る。

  • (1) : xsの各要素と、ysの各要素の論理積を得る。
  • (2) : xsの各要素と、yの論理積を得る。
  • (3) : ysの各要素と、xの論理積を得る。

戻り値

  • (1) : 以下のコードと等価のことを行う:

valarray<T> result = xs;
result &= ys;
return result;

  • (2) : 以下のコードと等価のことを行う:

valarray<T> result = xs;
result &= y;
return result;

  • (3) : 以下のコードと等価のことを行う:

valarray<T> result = ys;
result &= x;
return result;

備考

  • 引数、および、戻り値の型 ValOrProxy は、valarray、あるいは、その代理となる型である。
    <valarray> の概要も参照のこと。
  • (1) : xsys の要素数が異なる場合、その挙動は未定義
  • C++20における(2)と(3)に対する変更は、std::valarray<double>{} * 2 のような式が型推論に失敗しないようにするためである。
    なお、この変更は規格の誤り修正とみなされているため、処理系によっては C++17 以前でも使用可能となる。

#include <cassert>
#include <valarray>
#include <cstdint>
#include <algorithm>

template <class T>
bool equal_valarray(const std::valarray<T>& a, const std::valarray<T>& b)
{
  const std::valarray<bool> result = a == b;
  return std::all_of(std::begin(result), std::end(result), [](bool b) { return b; });
}

int main()
{
  const std::valarray<std::uint8_t> a = {
    0b00000101,
    0b00001010,
    0b00010101
  };
  const std::valarray<std::uint8_t> b = {
    0b00000011,
    0b00000011,
    0b00000011
  };
  const std::valarray<std::uint8_t> expected = {
    0b00000001,
    0b00000010,
    0b00000001
  };

  std::valarray<std::uint8_t> result1 = a & b;
  assert((equal_valarray(result1, expected)));

  std::valarray<std::uint8_t> result2 = a & 0b00000011;
  assert((equal_valarray(result2, expected)));

  std::valarray<std::uint8_t> result3 = 0b00000011 & a;
  assert((equal_valarray(result3, expected)));
}

出力

参照