0
我有一个C++代码,当前看起来像这样:有一个类层次结构来执行一些比较和使用它的列表类。基于某个模式对象在运行时确定要使用哪种比较操作。这里是结构:如何正确地用模板重写这个使用继承的C++代码
class A{
bool doComparison(const string& s1, const string& s2) const=0;
}
class B: public A{
bool doComparison(const string& s1, const string& s2) const {
...
}
}
class C: public A{
bool doComparison(const string& s1, const string& s2) const {
...
}
}
template <class, S>
public FancyList{
shared_ptr<A> z_;
vector<S> v;
FancyList(shared_ptr<A> z) : z_(z);
void DoSmth(){
....
z_->doComparison(arg1, arg2);
}
}
typedef FancyList<string> FancyStringList;
// Determine which comparison to use at runtime
shared_ptr<A> c = nullptr;
switch(type):
case int:
c = make_shared<B>();
break;
case double:
c = make_shared<B>();
break;
FancyStringList l(c);
l.push_back("stuff");
C#曾经是我的主要语言,所以这段代码对我来说似乎没问题。但我被告知,这种方法的问题在于它使用虚函数,因此在方法调用中会有一些小的开销。什么是适当的C++ - 重新组织这段代码的方式,所以不需要拥有这个类的层次结构,也不需要使用虚函数?
'do'是一个C++关键字。你不能用这个标识符来命名你的功能。 – StoryTeller
'在运行时基于某个模式对象确定要使用哪种比较操作'。这意味着无论如何,你的程序必须花费一些CPU圈来选择比较方法,对吧?然后,我认为这种轻微的开销在这种情况下是可以接受的,它使您的代码更易于阅读和**扩展**。 –
'switch'语句中的'type'是什么? –