我一直在使用" 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);
}
...
};
Run Code Online (Sandbox Code Playgroud)
不,这种用法是正确的:在类模板内,类名引用模板的该实例,因此模板参数不是必需的:
template<typename T>
struct foo
{
foo( const foo& ); //Copy ctor. foo is the same as foo<T>
};
Run Code Online (Sandbox Code Playgroud)
这种行为在14.6.1 标准的本地声明名称(强调我的)中得到了很好的定义:
14.6.1 本地声明的名称 [temp.local]
与普通(非模板)类一样,类模板也有一个注入类名称(第 9 条)。注入类名可以与或不与模板参数列表一起使用。当它在没有 template-argument-list 的情况下使用时,它相当于注入的类名,后跟 <> 中包含的类模板的模板参数。当它与 template-argument-list 一起使用时,它指的是指定的类模板特化,可以是当前特化或另一个特化。
请注意,语法只是当前模板实例的别名。如果您需要具有其他参数的相同模板,则需要使用经典语法显式指定它。例如:
template<typename U>
operator foo<U>() const //Implicit conversion to other instance of the template
{
return ...;
}
Run Code Online (Sandbox Code Playgroud)