我意识到提问是多么困难...希望我能给出足够精确的示例来展示我的问题,并且足够简短以免混淆一切...至少还可以编辑。
所以这就是我的目前情况。当然,我在逻辑/结构上稍微改变了一些(无论如何,在命名方面也有所改变),试图集中于我的问题的本质:
// 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);
}
}
目前我更倾向于选择可能性1,因为我不需要在提取器中处理所有MyType变体和相关提取器的继承问题,这也方便我在未来尝试其他变体。
另一方面,提取器可能需要复杂的代码和多个成员(例如将某些输入映射到特定值的大型映射表)。因此,使用模板不会带来性能收益。特别是仅使用头文件的提取器,甚至是预计要内联的函数对象,都不太可行。过去,这让我强烈感觉到,模板只会增加代码复杂性(必须处理实例化,使客户端代码更加困难等),因此我应该尽量避免使用它。
或者,还有第三种可能性我没有考虑吗?