替代虚拟typedef [英] alternative to virtual typedef

查看:95
本文介绍了替代虚拟typedef的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个IEnumerable接口,用于List<>,Array<>和Dictionary<>的模板类.我希望使用typedef来获取其模板化类型T.

I have an interface IEnumerable for template classes of List<>, Array<> and Dictionary<>. I was hoping to use typedef to get their templated types T.

我希望做到以下几点.

class IEnumerable
{
public:
    virtual typedef int TemplateType;
}

然后在继承的成员中重写,但是您不能进行虚拟typedef.那么,还有其他方法可以获取未知模板类的类型(IEnumerable不是模板)吗?

And then override in inherited member, but you cant make a virtual typedef. So is there any other way that i could get the type of an unknown template class (IEnumerable is not template)?

推荐答案

好吧,这是注释中讨论的内容,以防以后有相同问题的人找到它.

Well, here is what is discussed in the comments in case somebody with the same question later finds this.

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

Basically, you want to do something similar to C#'s List<>, Array<>, IEnumerable and IEnumerator. However, you don't want to have to create a generic parent class Object because it may mean that you'll need to dynamic_cast every time.

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

Additionally, you don't want to make IEnumerable a template because you don't want to have to know the type when using the collection.

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

In fact, with C++11, you can make IEnumerable a template and not have to know the type by using the implicit type keyword auto, which is the C++11 equivalent of c#'s var keyword.

为此,您可以做的是:

 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
  }

最后,在使用它时,您可以执行以下操作:

Finally, when it comes to using it, you can do:

  List<int> myList;


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

这篇关于替代虚拟typedef的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆