模板什么时候结束?
我们来看看这段代码:
template <class T>
class thatClass
{
T a, b;
thatClass (T x, T y) {a = x; b = y;}
};
template <class T>T aFunc(T one, T two)
{
return one+two;
}
那么什么时候template <class T>
结尾?它总是在类或函数定义结束之后结束吗?为什么不能只使用为类和函数声明的一个模板,所以在这种情况下,我可以使用模板参数T
对于这两个函数aFunc
以及类定义?
模板参数的范围以模板化主题的范围结束:
template <class T>
class thatClass
{
T a, b;
thatClass (T x, T y) {a = x; b = y;}
}; // << ends here
template <class T>T aFunc(T one, T two)
{
return one+two;
} // << ends here
为什么不能只使用为类和函数声明的一个模板,所以在这种情况下,我可以使用模板参数T
对于这两个函数aFunc
以及类定义?
不能,因为模板参数范围始终绑定到类/结构或函数定义。这在语言中是这样定义的。
人们可以考虑对整体进行模板化namespace
,但这不是可用的语言功能,而且我不确定这是否是一个好主意。
由于您似乎很困惑,我将添加一些变化:
template <class T>
class thatClass
{
T a, b;
thatClass (T x, T y) {a = x; b = y;}
// A member funcion that uses the same template parameter and accesses
// the class member variables
T aFunc() { return a+b; }
// A static member funcion that uses the same template parameter and
// calculates the result from the parameters
static T aStaticFunc(T one, T two) { return one+two; }
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)