alternative to virtual typedef

你说的曾经没有我的故事 提交于 2019-12-22 05:54:30

问题


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.

I was hoping to do the following.

class IEnumerable
{
public:
    virtual typedef int TemplateType;
}

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)?


回答1:


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

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.

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.

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.

So to do this, what you can do is:

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

then

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

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

and

  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;


来源:https://stackoverflow.com/questions/14741442/alternative-to-virtual-typedef

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!