假设我有一个类,比如:
template<class TYPE>
class RandomAccessBox {
//...
public:
void insert (TYPE x){
//insert something into the box
}
int size(){
//return number of elements in the box
}
TYPE randomaccess(){
//return random object in the box
}
TYPE deletelast(){
//delete last item accessed from the box
}
};
我的程序到处都使用 RandomAccessBox。
现在假设我想要一些运行时特化。也就是说,当初始化我的 RandomAccessBox 时,我想将它设置为类型 1 或类型 2,比方说(并且类型永远不会改变)。类的函数和成员对于这两种类型都是相同的,但我希望能够根据类型简单地更改函数的行为。 (例如,也许我想改变事物的存储和随机访问方式)。
关键是我不希望其余代码必须关心我拥有哪种类型的 RandomAccessBox,因为面向公众的函数和成员将是相同的,并且这两种类型在相同的环境中使用方式。
特别是,我希望能够拥有像这样的功能
void statisticsonbox(RandomAccessBox mybox){
//do some stuff with mybox
}
与 mybox 的类型无关。
显然,我可以使用一个内部变量来存储类型,然后根据该变量的状态设置每个函数案例。但是,这个 RandomAccessBox 是“在内部循环中”,因此与此相关的任何惩罚都是一个问题。 (也许实际上,对于现代处理器,这样的外壳基本上没有任何损失?)
我也可以使用函数指针。
还有其他方法可以做到这一点吗?
最佳答案
This RandomAccessBox is "in the inner loop", though, so any penalty associated with that is a problem. (Perhaps realistically there is essentially no penalty from casing like this with modern processors?)
您需要为依赖于 RandomAccessBox
的整个代码部分使用模板。例如:
template <class TYPE>
void statisticsonbox(RandomAccessBox<TYPE> mybox){
//do some stuff with mybox
}
否则,您将不得不以某种方式确定每次迭代的行为(使用虚拟方法、类型确定和分支等),这将不可避免地导致性能损失(如果这对您的情况真的很重要)。这种方法可能会导致问题 - 编译时间增加、输出文件大小增加、更改代码的重要部分以使用模板。您需要将依赖于类型的部分和独立于类型的部分分开,并选择最佳比例。
关于具有在初始化时定义的不同行为的 C++ 成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54538888/