我刚刚意识到要问的问题有多难......希望我能给出的例子都足够精确,足以证明我的问题,并且足够短以避免混淆一切......至少有这种可能性编辑。C++模板与继承
所以这是我目前的情况。当然,我改变了一点逻辑/结构方面(以及反正命名方面)试图把重点放在我的问题的实质:
// MyClass deals with lists (actually several data structures) of the
// type MyType which should support different types and has to be
// efficiently dealt with. Templating seems just right here
class MyClass
{
...
void doSomething<class MyType>(vector<MyType> someList);
...
// At some point I have to extract elements of the type MyType.
// The extractor obviously depends on MyType but it is not possible to
// Create a general version that could use templates itself
// (unless I use a specialization for each possible MyType)
// I am stuck between these two alternatives:
// Possibility1:
// Let the client pass the right extractor and template it.
template<class Extractor, class MyType>
void extract(const Extractor& extractor, const string& source,
vector<MyType>* dest)
{
extractor.extract(source, dest);
}
// Possibility2:
// Use a member _extractor of some base type that has to be set
// to a specialization. The ExtractorBase has a virtual method
// template<T> void extract(const string& source, vector<T>* myType) = 0
// with no definition that is only defined in subclasses wrt certain
// postings.
ExtractorBase _extractor;
template<class MyType>
void extract(const string& source, vector<MyType>* dest)
{
_extractor.extract(source, dest);
}
}
此刻,我宁愿possibility1,因为我不我不得不在抽取器中继承MyType和相关抽取器的所有变体,我想在将来尝试。另一方面,提取器可能需要复杂的代码和若干成员(如某些输入值映射到特定值的巨大映射)。所以使用模板不会有性能提升。特别是只使用头文件提取器,甚至可能是内联的函子,都是不可能的。在过去,这对我来说是一个强烈的指向,即模板只会增加代码的复杂性(不得不处理实例化,使客户代码更难生活等),并且我应该尽量避免它。
或者还有第三种可能性我根本没有想到?
“提取”是什么意思?是否只使用矢量? –
vines
目前还不清楚MyClass如何参与抽取过程(以及为什么extract()是MyClass的_method_) – user396672