0

A と B の 2 つのクラスがあります。クラス A は、指定されたベクトルに対して変換を実行する変換 (行列) です。

class A{ 
public:
     ...
     A(...){};
     ...
     void func_A(std::vector<double>& vec){
        /* Transform vector vec */
     }
};

クラス B には 2 つのメンバーがあります。std::vector<double> &vecベクトルの参照、およびconst std::vector<std::shared_ptr<A> > &a_ptrsクラス A の共有ポインタを含む別のベクトルの定数参照であり、異なる変換を表します。a_ptrsゼロ、1 つ、または複数の変換を含めることができます。クラス B の仕事の 1 つは、これらの (もしあれば) 変換を vector に適用することvecです。

class B{
public:
    std::vector<double> &vec;
    const std::vector<std::shared_ptr<A> > &a_ptrs;

    B(std::vector<double> &vec_ref) : vec(vec_ref){
     /* How to initialize a_ptrs if there are no transformations available? 
      That is, there are no shared pointers of class A available.*/
    }        

    B(std::vector<double> &vec_ref,
      const std::shared_ptr<A> &aptr) : vec(vec_ref){
      /* How to initialize a_ptrs if there is only one transformation available, and 
      I just decide to pass a const reference to the shared pointer of A? */
    } 

    // No issues with this constructor:
    B(std::vector<double> & vec_ref, 
      const std::vector<std::shared_ptr<A> > &aptr) : vec(vec_ref), a_ptrs(aptr){}

    void func_B(){
         ...
         // Apply the transforms:
         for(int i=0; i<a_ptrs.size(); ++i){
             a_ptrs[i]->func_A(vec);
         }
         ....
    }
};

この目的のために、ご覧のとおり、クラス B のコンストラクターをオーバーロードしました。const std::vector<std::shared_ptr<A> > &a_ptrsが引数として B のコンストラクターに渡されると、すべて問題ありません。a_ptrsしかし、私の問題は、利用可能な変換が 0 または 1 つしかない場合、つまり、それぞれ空であるか要素が 1 つしかない場合に、この定数参照を初期化する方法がわからないことです。

要素が 1 つしかない場合は、 を渡すだけで、それに基づいて何らかの 方法で初期化a_ptrsできるようにしたいと考えています。const std::shared_ptr<A> &aptra_ptrs

また、クラス B のクラス A への共有ポインターのコピーを作成したくありません。共有ポインターへの定数参照も必要です。

インターネットで見つけたものに基づいて、boost::optionalまたはを使用する可能性がありますが、std::experimental::optional機能させることができませんでした。

私は c++ の初心者で、この問題に 2 日間取り組んできましたが、うまくいきませんでした。どうすればこの問題を克服できますか? 別の設計戦略を立てる必要がありますか? この問題の解決に役立つコメントや提案をいただければ幸いです。

4

1 に答える 1