这是一些代码:
class IWorker {
public:
virtual void Do(int x) const = 0;
};
class TSomeWorker : public IWorker {
void Do(int x) const {
// ...
}
};
现在,假设我们需要重构它,使函数 Do 变成模板(int 变成一些 T)。我知道 C++ 不允许创建模板虚函数。有其他选择吗?
最佳答案
这取决于您的具体需求。但根据您发布的内容,我建议:
template<typename T>
class IWorker {
public:
virtual void Do(T x) const = 0;
};
template<typename T>
class TSomeWorker : public IWorker<T> {
void Do(T x) const {
// ...
}
};
关于c++ - 模板虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11299261/