我最近一直在做一个小项目,但我无法弄清楚一些事情。
我得到了一个 .h 文件,其中包含一个使用类型名模板的类。那个班级里面有一个私人班级。
template <typename T>
class Something
{
public:
Something();
~Something();
Node* Function1(int index);
int Index(const T& id);
private:
class Node()
{
public:
T id;
//Imagine the rest for the Node
};
};
当我想定义“Something”类的函数时出现了问题
这是我的做法(在 .inl 文件中)
template<typename T>
Node* Something::Function1(int index) //Is the return type well written?
{
// returns the node at the specified index
}
template<typename T>
int Something::Index(const T& id) //Is the parameter type well specified?
{
// returns the index of the node with the specified id
}
所以错误部分在定义部分......我是否必须告诉编译器返回类型(在本例中为 Node*)使用类型名模板(如下所示:typename Node*
)?那么参数呢?typename const Node&
?
所以基本上,我什么时候必须指定函数/参数是否使用模板?
谢谢你的时间。
For Function1
,您需要告诉编译器 Node 是什么——在本例中,它是内部的嵌套类型Something<T>
。因为它依赖于T
(它是一个从属名称),您需要告诉编译器它是一种类型,因此您必须将其写为typename Something<T>::Node
。问题是可能有一些T
为此Something<T>::Node
实际上不是一种类型(即,如果您部分专业化Something<T>
).
For Index
,你拥有的很好--const T&
只是一个参考const T
,编译器知道什么T
is.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)