我才意识到提出问题是多么困难……希望我能举出足够精确的例子来证明我的问题,而且足够简短,不会把所有事情都搞砸……至少有编辑的可能。
所以这就是我目前的情况。当然,我在逻辑/结构(以及无论如何命名)方面对其进行了一些修改,试图专注于我的问题的本质:
// 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 变体和相关的 Extractor 的 Extractor 中的继承搞乱。
另一方面,提取器可能需要复杂的代码和多个成员(例如将某些输入映射到某些值的巨大映射)。所以使用模板不会有性能提升。特别是仅使用头文件的提取器,甚至可能是应该内联的函子,都是不可能的。在过去,这对我来说是一个强有力的指针,模板只会增加代码复杂性(必须处理实例化,使客户端代码的生活更加困难等),我应该尽量避免它。
还是我根本没有想到的第三种可能性?