0

C++ で式テンプレートを調べようとしています。基本的に3つのコンポーネントを持つ座標、空間ベクトル、力などを格納するための3Dベクトル(基本的にサイズ3のベクトル)のクラスを作成しようとしています。

これまでのところ、2 つのベクトルの合計を実行するクラスのみを実装しました。私が書いた場合、コードは正常に動作しますvector3d z; z = x + y;。つまり、最初に z 変数を宣言してから加算を実行するとします。vector3d z = x + y;しかし、一文で書こうとするとエラーになります。私は得るerror: conversion from 'const ExprSum<vector3d, vector3d>' to non-scalar type 'vector3d' requested vector3d z_new = x + y ;

=変数宣言時に使用できるようにするには、どのように実装すればよいですか?

以下は私の完全なコードです:

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

using namespace std;

/** @brief The base expression class */

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); }
};


/** @brief The vector3d class : The vector<double> with 3 elements */

class vector3d : public Expr<vector3d> {
private:
  container_type _data;
public:
  vector3d():_data(3){}
  vector3d(const vector3d& _rhs){
      *this = _rhs;
  }

  size_type  size() const { return _data.size(); } // should return 3.

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

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

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

};

/** @brief class for summation of vectors  */

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

  typedef vector3d::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_t size() const { return _u.size(); }
};


/** @brief wrapper function of ExprSum class */
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()
{
    vector3d x,y;

    x[0] = 1;
    x[1] = 2;
    x[2] = 3;

    y[0] = 5;
    y[1] = 4;
    y[2] = 0;

    // works fine
    vector3d z;
    z = x + y;

    vector3d z_new = x + y ; // get error

    return 0;
}
4

1 に答える 1