如何引用参数参数的嵌套模板中的类型?
假设我有以下定义
template <class T>
class Sequence
{
}
例如 Sequence
可能是一个字符串数组,类似于 vector
// Now define iterator template
template <class T>
class SequenceIterator
{
}
这里的想法当然是能够在某个序列上创建迭代器 例如,
SequenceIterator< Sequence<string> > iter1;
SequenceIterator< Sequence<int> > iter2;
我现在的问题是如何定义 SequenceIterator 中存在的成员函数,其目的是返回序列中的下一个值。通常,我希望将其写为然而
bool Next(T1 & value); // If the iterator has not finished, set value to the next item
,SequenceIterator
已以模板化名称传递,即 Sequence
或 Sequence
所以问题是,我如何一般地引用该基础类型(string
或 int
),以便我可以定义 Next 成员函数。
谢谢, 大卫
Suppose I have the following definitions
template <class T>
class Sequence
{
}
E.gSequence<string>
might be an array of strings, similar to vector<string>
// Now define iterator template
template <class T>
class SequenceIterator
{
}
The idea here of course is to be able to create an iterator over some sequence
E.g.
SequenceIterator< Sequence<string> > iter1;
SequenceIterator< Sequence<int> > iter2;
The question I now have is how to define the member function that would exist inside SequenceIterator and whose purpose is to return the next value in the sequence. Typically I would expect to write that as
bool Next(T1 & value); // If the iterator has not finished, set value to the next item
However, the SequenceIterator
has been passed in a templated name already, i.e, Sequence<string>
or Sequence<int>
So the question is, how do I generically refer to that underlying type (string
or int
) so that I can define the Next member function.
Thanks,
David
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有三种方法:更改
Sequence
的定义以包含,或者更改
SequenceIterator
的模板参数以明确识别Sequence
本身是模板虽然
SequenceIterator
的实例化没有改变,但您现在可以直接访问T
。第三,您可以使用容器特征类来处理为您类型扣除。第三个选项提供了Sequence
和SequenceIterator
之间的最小耦合,但是,就像 马克说,标准容器倾向于使用第一种方法。There are three ways: change the definition of
Sequence
to includeor, change the template parameters for
SequenceIterator
to explicitly recognize thatSequence
is a template itselfand while the instantiation of
SequenceIterator
does not change, you can now accessT
directly. Thirdly, you can use a container traits class that handles the type deduction for you. The third option provides the least coupling betweenSequence
andSequenceIterator
, but, like Mark said, the standard containers tend to use the first method.标准库通过在每个容器中包含 typedef 来解决这个问题。在这种情况下,
Sequence
将具有typedef T value_type;
,因此您可以使用Sequence::value_type
来引用那种类型。另外,我会高度考虑像标准库一样使用
operator++
和operator*
,这样就不会让人对非标准迭代器接口感到困惑。The standard library solves this by having typedefs within every container. In this case
Sequence<T>
would have atypedef T value_type;
so you can then useSequence<T>::value_type
to refer to that type.Also, I would highly consider using
operator++
andoperator*
like the standard library so you don't confuse people with a non-standard-like iterator interface.