【发布时间】:2020-06-10 05:42:04
【问题描述】:
假设我有以下class A,它通过不同的函数调用和包装器传递。
class A{
std::vector<int> a;
public:
int getSize const {return a.size();}
int getVal(int i) const {return a[i];}
// other private and public members and functions
}
现在出于某种原因,我需要相同的类,但使用双向量。我无法对此类进行模板化,因为有许多我无法更改的函数签名。建议将A 重命名为A0,将其模板化,创建包含A0<int> 和A0<double> 的新A,如下所示:
template <typename T>
class A0{
std::vector<T> a;
public:
int getSize const {return a.size();}
T getVal(int i) const {return a[i];}
// other private and public members and functions
}
class A{
// only one of the following will be initialized in the constructor and the other one will be null.
std::shared_ptr<A0<int>> iA;
std::shared_ptr<A0<double>> dA;
// also the following flag will be set in the constructor
bool isInt;
}
这是一个问题:如果我想在之前访问、更改或刚刚传递类A 的实例的代码的不同位置进行最小的更改,应该怎么做?例如,在旧代码的不同部分考虑这一点:
A x;
int n = x.getSize();
有没有办法保留旧代码,而无需在新的 A 类中实现方法 getSize(),该类将包含 if 条件语句并基于 isInt 返回 iA->getSize() 或 dA->getSize()?有没有聪明的方法来做到这一点?
对于在使用(主要是绕过)旧A的代码的不同部分实现最小修改的目标,是否有任何其他建议?
}
【问题讨论】:
-
您期望什么类型,例如
getVal在不破坏之前依赖它的代码的情况下返回int? -
当然这不是真正的代码,但是在这种地方,它会针对每种情况进行专门处理。大多数情况下,此类仅从一种方法传递到另一种方法,直到它到达完成实际操作的方法(并且可以针对那里的每种情况处理事情)
标签: c++ class templates call function-call