c++pointersoperator-keywordvalarray

Operator += applied to std::valarray<int*>


Here is the example:

    #include <iostream>
    #include <string>
    #include <valarray>

    int main()
    {
      std::valarray<std::string> vs(2);
      // vs[0] += "hello"; // works
      // vs[1] += "hello"; // works
      vs += "hello"; // works
      std::cout << vs[0] << std::endl;
      std::cout << vs[1] << std::endl;

      std::valarray<int*> vi(2);
      vi[0] = new int[2];
      vi[0][0] = 0;
      vi[0][1] = 1;
      vi[1] = new int[2];
      vi[1][0] = 2;
      vi[1][1] = 3;
      std::cout << vi[0][0] << std::endl;
      std::cout << vi[1][0] << std::endl;
      // vi[0] += 1; // works
      // vi[1] += 1; // works
      vi += 1; // error: invalid operands of types 'int*' and 'int*' to binary 'operator+'
      std::cout << vi[0][0] << std::endl;
      std::cout << vi[1][0] << std::endl;
    }

I don't understand this error, if someone may explain this to me.

Is there a workaround?

Best regards,


Solution

  • std::valarray doesn't have overloads for heterogeneous binary operations, but it does have a catch-all for other functions, apply.

    vi.apply([](int * p){ return p + 1; });