我一直在使用“const ObjArray&
”作为 ObjArray 模板的参数,但没有考虑它。它似乎工作正常,但当我再次阅读时它看起来很糟糕。不应该是“const ObjArray<T> &
”吗?不带参数引用模板名可以吗?它是否在下面工作只是因为编译器假定 T 被声明为内联?
template <class T>
class ObjArray : public BArray
{
public:
inline ObjArray() :
BArray(sizeof(T), NULL)
{
}
inline ObjArray(const ObjArray& src) :
BArray(sizeof(T), NULL)
{
copyFrom((ObjArray&)src);
}
inline ObjArray(ObjArray& src) :
BArray(sizeof(T), NULL)
{
copyFrom(src);
}
...
};
不,这种用法是正确的:在类模板中,类名指的是模板的那个实例,所以模板参数不是必需的:
template<typename T>
struct foo
{
foo( const foo& ); //Copy ctor. foo is the same as foo<T>
};
此行为在标准的 14.6.1 本地声明名称 点中有明确定义(强调我的):
14.6.1 Locally declared names [temp.local]
Like normal (non-template) classes, class templates have an injected-class-name
(Clause 9). The injected-class-name can be used with or without a
template-argument-list. When it is used without a
template-argument-list, it is equivalent to the injected-class-name
followed by the template-parameters of the class template enclosed in
<>. When it is used with a template-argument-list, it refers to the
specified class template specialization, which could be the current
specialization or another specialization.
请注意,syntax 只是当前模板实例的别名。如果您需要具有其他参数的相同模板,则需要使用经典语法明确指定它。例如:
template<typename U>
operator foo<U>() const //Implicit conversion to other instance of the template
{
return ...;
}