我正在写一个容器模板,
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/