考虑模板类什么时候我们必须明确地引用模板,当编译器"理解我们的意思"时
考虑以下事件:
1)功能返回值和争论
2)函数内部的变量声明
3)命名空间SomeClass<T>::
vs.SomeClass::
有规则吗?我看到有时使用的是:
SomeClass
Run Code Online (Sandbox Code Playgroud)
而有时: SomeClass<T>
我没有得到规则
类模板参数只能在该类的实现中被省略,它们隐式地将适当的模板说明符添加到类中,并且在引用非依赖基类时(非依赖如“不重用任何模板参数”) 。例如:
template<typename T, typename U>
class C { /* here C is the same as C<T, U> */ };
template<typename T>
class C<void, T> { /* here C is the same as C<void, T> */ };
template<>
class C<void, void> { /* here C is the same as C<void, void> */ };
template<typename> struct Base { };
struct DerivedA : Base<void>
{ /* here Base is the same as Base<void> */ };
template<typename T>
struct DerivedB : Base<T>
{ /* here Base is invalid, since Base<T> depends on a template argument */ };
Run Code Online (Sandbox Code Playgroud)
函数模板可以省略它们的模板参数,如果它们可以从它们的参数推断出来的话:
template<typename T>
void f(T f);
f(3); // equivalent to f<int>(3) if no other overload exists
Run Code Online (Sandbox Code Playgroud)
此外,还有默认的模板参数,这会导致一些非常有趣的事情:
template<typename T = void>
class D
{
// Here D is D<T>, but D<> is D<void> instead!
};
Run Code Online (Sandbox Code Playgroud)