c++ - 替代虚拟类型定义

标签 c++ templates polymorphism typedef

我有一个用于 List<>、Array<> 和 Dictionary<> 模板类的 IEnumerable 接口(interface)。我希望使用 typedef 来获得他们的模板化类型 T。

我希望做以下事情。

class IEnumerable
{
public:
    virtual typedef int TemplateType;
}

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

最佳答案

好吧,这里是评论中讨论的内容,以防有相同问题的人后来发现这一点。

基本上,您想做一些类似于 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;

关于c++ - 替代虚拟类型定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14741442/

相关文章:

c++ - 类型定义枚举的问题。和 visual studio 2005 中的错误

c++ - 有没有让我们将 "pass a namespace"放入模板的技巧?

c++ - 编译器如何解析函数?

c# - 为什么泛型约束不能帮助编译器在具有可选参数的多态方法中做出决定?

java - 如何在对现有类进行本地继承的同时实现接口(interface)

C++:在 Msys 下使用使用 g++ 和 -m32 选项构建的 c++ 库构建 wxWidgets 项目时出现 ld 不兼容错误

c++ - 删除 char* 进行字节转换

c++ - GPU 加速 LK 金字塔中的窗口大小限制

css - 如何在tailwindcss中使用模板文字来动态更改类?

c++ - C++ 中查找子数组的模板函数