c++ - 声明一个与该模板的实例具有相同类型的变量

标签 c++ templates

我正在写一个容器模板,

template <typename T, typename S>
class Container
{
    public:
       S size(void) const { return mItems; }

    private:
       S mItems;
       S mMaxItems;
       T *mArray;
};

在代码中我想这样做:

Container<Rooms, int> RoomCtr;

for(RoomCtr::type i = 0; i < RoomCtr.size(); i++)
{
}

以便变量匹配 S 类型,而无需我指定 int 硬编码。

这可能吗?

到目前为止我发现的唯一方法是:

template <typename T, typename S>
class Container
{
    S type(void) const { return 0; }
    ...
};


for(decltype(Table.type()) i = 0; i < RoomCtr.size(); i++)
{
}

我想知道是否有更好的方法。或者这是正确的方法吗?

我目前使用的是 Visual Studio 2010。

最佳答案

你可以做一个简单的typedef:

template <typename T, typename S>
class Container {
  T *data;
  /* other variables */

  public:
    typedef S size_type;
    Container();

};

int main() {
  Container<char, int>::size_type something;
}

这里 something 的类型是 int

关于c++ - 声明一个与该模板的实例具有相同类型的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36451686/

相关文章:

matlab - 使用归一化互相关匹配对象外形

c++ - 具有可变高阶函数的重载分辨率

C++ 模板化 STL 容器

c# - 我们应该把枚举放在哪里?

c++ ceil() in stooge sort 不工作

c++ - 将鼠标光标隐藏在 Windows 中的特定客户区域

c++ - 通过串联创建原始字符串时,是否会还原三字母替换?

java - 内存分配究竟是如何进行的,Java 和 C 如何交互以跟踪同一个对象?

c++ - 使用 gcc 编译代码后,std::out_of_range 异常字符串不会打印

java泛型类扩展了泛型参数