我有两个类,A 和 B。A 类是对给定向量执行变换的变换(矩阵)。
class A{
public:
...
A(...){};
...
void func_A(std::vector<double>& vec){
/* Transform vector vec */
}
};
B类有两个成员;std::vector<double> &vec
一个向量的引用,以及const std::vector<std::shared_ptr<A> > &a_ptrs
另一个向量的常量引用,该向量包含 A 类的共享指针,表示不同的转换。a_ptrs
可能包含零个、一个或多个转换。B 类的工作之一是将这些(如果有的话)转换应用于 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
分别为空或只有一个元素。
如果a_ptrs
只有一个元素,我希望能够传递 a ,并以此为基础进行 const std::shared_ptr<A> &aptr
初始化。a_ptrs
我也不想在 B 类中复制指向 A 类的共享指针。我也希望对共享指针有一个常量引用。
根据我在互联网上的发现,有可能使用boost::optional
or std::experimental::optional
,但我无法使其工作。
我对 c++ 很陌生,我已经在这个问题上工作了两天,没有任何运气。我该如何克服这个问题?我应该有另一种设计策略吗?我将不胜感激任何有助于我解决此问题的意见或建议。