【问题标题】:alternative to virtual typedef替代虚拟类型定义
【发布时间】:2013-02-07 00:18:53
【问题描述】:

我有一个接口 IEnumerable 用于 List、Array 和 Dictionary 的模板类。我希望使用 typedef 来获取他们的模板类型 T。

我希望做以下事情。

class IEnumerable
{
public:
    virtual typedef int TemplateType;
}

然后在继承的成员中覆盖,但你不能创建一个虚拟类型定义。那么有没有其他方法可以获取未知模板类的类型(IEnumerable 不是模板)?

【问题讨论】:

  • 重新标记为 C#,因为据我所知 virtual typedef 不是 C++ 功能。
  • @templatetypedef 你读过这个问题吗?!我说 virtual typedef 不起作用,并询问有关替代方案的意见。请取消标记!
  • 抱歉 - 因为您使用的类型名称如 IEnumerableListArrayDictionary,我认为这是 C# 代码(因为这些类型没有内置到C++)。很抱歉!
  • 不,你不能那样做。类型将在编译时解析,因此动态类型在其中没有位置。
  • 是的隐式类型。没错。

标签: c++ templates polymorphism typedef


【解决方案1】:

嗯,这就是 cmets 中讨论的内容,以防以后有相同问题的人发现。

基本上,您想做一些类似于 C# 的 List、Array、IEnumerable 和 IEnumerator 的事情。但是,您不希望必须创建通用父类 Object,因为这可能意味着您每次都需要进行 dynamic_cast。

此外,您不想让 IEnumerable 成为模板,因为您不想在使用集合时知道类型。

事实上,在 C++11 中,您可以使 IEnumerable 成为模板,而不必通过使用隐式类型关键字 auto 知道类型,即C++11 等效于 c# 的 var 关键字。

所以要做到这一点,你可以做的是:

 template <class T>
 class IEnumerable { 
     public:
        virtual IEnumerator<T> getEnumerator() = 0; 
        // and more stuff
 }

然后

  template <class T>
  class List : public IEnumerable<T> { 

  public:
         virtual IEnumerator<T> getEnumerator() { 
               return ListEnumerator<T>(this); 
         }
  }

  template <class T>
  class ListEnumerator : public IEnumerator<T> { 
  public:
        T getNext();   // or something to this effect
        // and more stuff
  }

最后,在使用它的时候,你可以这样做:

  List<int> myList;


  auto i = myList.getEnumerator();
  int z = i.getNext()+1;

【讨论】:

  • +1 一个很好的总结。现在连我都更明白了:P
  • 我也可以做 ListEnumerator = myList.getEnumerator(); ?
  • 我可以 typedef auto (aka typedef ListEnumerator ListEnum;)
  • 你在开玩笑吗?! List 有效! naaaa 我不相信。即使对于 c++ 来说,它也太棒了:明天我会检查一下
  • 其实我不知道。我以为你试过了!事实证明它不起作用;但是, boost::any 的工作方式相同。 stackoverflow.com/questions/12176972/…
猜你喜欢
  • 2017-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多