C ++ fuzzy syntax on operator overloading

I'm still new to C ++ and trying to understand Expression patterns. I came across a sample Wikipedia code . I read most of the program and how it works, but I donโ€™t understand how these lines are interpreted by the compiler:

 operator A&()             { return static_cast<      A&>(*this); }
 operator A const&() const { return static_cast<const A&>(*this); }

from the base class of the expression template below. Usually the operator overload syntax is return_datatype operator+ (args){body}(for example, for the + operator), but this gives errors, and the functions in the compilation compile without any error. Can someone explain these two lines? What to do A&and A const&before the operation? And why A& operator() (){}and A const& operator() (){}do not work? This gives an error:

no matching function for call to 'Vec::Vec(const Expr<Vec>&)'
   ExprSum(const Expr<A>& a, const Expr<B>& b): _u(a), _v(b) {}

-Pranav

Full code:

#include <iostream>
#include <vector>
#include <cassert>

using namespace std;


template <class A>
class Expr{
public:
  typedef std::vector<double>         container_type;
  typedef typename container_type::size_type   size_type;
  typedef typename container_type::value_type  value_type;
  typedef typename container_type::reference   reference;

  size_type size() const  {return static_cast<A const&>(*this).size(); }
  value_type operator [] (size_t i) const {return static_cast<A const&> (*this)[i];}
  operator A&()             { return static_cast<      A&>(*this); }
  operator A const&() const { return static_cast<const A&>(*this); }
};


class Vec : public Expr<Vec> {
private:
  container_type x;
public:
  Vec(){}
  Vec(size_type length) :x(length) {}
  size_type  size() const { return x.size(); }

  reference operator [] (size_type i){
    assert(i < x.size());
    return x[i];
  }
  value_type operator [] (size_type i) const {
    assert(i < x.size());
    return x[i];
  }

  template <class A>
  void operator = (const Expr<A>& ea){
    x.resize(ea.size());
    for(size_t i = 0; i < x.size(); i++){
      x[i] = ea[i];
    }
  }

};


template <class A, class B>
class ExprSum : public Expr <ExprSum <A,B> >{
private:
  A _u;
  B _v;
public:
  typedef Vec::size_type size_type;
  typedef Vec::value_type value_type;

  ExprSum(const Expr<A>& a, const Expr<B>& b): _u(a), _v(b) {}
  value_type operator [] (size_t i) const { return (_u[i] + _v[i]); }
  size_type size() const { return _u.size(); }
};


template <class A, class B>
ExprSum <A,B> const operator + (Expr<A> const& u, Expr<B> const& v){
  return ExprSum <A,B> (u,v);
}



int main(){

  size_t n = 10;
  Vec x(n);
  Vec y(n);
  Vec z;

  for(size_t i = 0; i < n; i++){
    x[i] = i;
    y[i] = 2*i;
  }

  z = x + y;

  cout << z[7] << endl;

  cout << "Hello world!" << endl;
  return 0;
}
+4
1

. , , .

+4

Source: https://habr.com/ru/post/1568824/


All Articles