C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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);
  }
}

目前我更喜欢possible1,因为我不需要在Extractor中使用myType的所有变体以及我想在将来尝试的相关Extractor中使用继承.

另一方面,提取可能需要复杂的代码和几个成员(类似于映射特定值的某些输入的巨大地图).因此,使用模板不会带来性能提升.特别是使用头文件只有Extractors,甚至可能是内联的仿函数,都是不可能的.在过去,这一直是我的一个强有力的指针,模板化只会增加代码复杂性(必须处理实例化,使客户端代码的生活变得更加困难等),并且我应该尽量避免使用它.

或者有没有第三种可能性我完全没有想到?

解决方法

最好选择第一个选项.它更清洁,更易于维护.

因为根据你的评论,我发现你正在为第二个选项做出错误的假设:

// The ExtractorBase has a virtual method
// template<T> void extract(const String& source,vector<T>* myTypE) = 0;

没有.那是不可能的;模板函数永远不可能是虚拟的.因此,要实现第二个选项,您必须选择一些肮脏且难以维护的方法,这不是一个好主意.

大佬总结

以上是大佬教程为你收集整理的C模板与继承全部内容,希望文章能够帮你解决C模板与继承所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:c模板继承