有谁知道为什么在定义模板方法时返回类型需要模板参数而不是参数类型?一个例子:
template<typename T>
struct Car {
Car drive(Car); // will be defined after the template declaration.
};
// Attempt #1: does not compile.
// Error: use of class template Car requires template arguments
template<typename T>
inline Car Car<T>::drive(Car) {}
// Attempt #2: compiles!
// The only difference is the use of template argument in return type.
// However, note that the argument to func does not require template argument!
template<typename T>
inline Car<T> Car<T>::drive(Car) {}
不确定为什么返回类型需要模板参数但参数类型不需要模板参数。当尝试 #1 失败时,我预计尝试 #2 也会失败,并预计我需要:
template<typename T>
inline Car<T> Car<T>::drive(Car<T>) {} // but no need to go this far.
但是尝试 #2 成功了!
这种行为有充分的理由吗?
最佳答案
首先,您承认这没有意义:Car c;
, 正确的? Car
必须有模板参数。这就是为什么您需要在返回类型和类名上指定它。
但在范围解析运算符 ( ::
) 之后,Car<T>
被注入(inject)为Car
*,所以 Car
是 Car<T>
的别名.但这只发生在 Car<T>
的范围内,这就是为什么你在其他任何地方都需要它,而不是在 ::
之后.当然,无论如何您都可以自己明确指定参数。
*这个特性最好这样解释:
template <typename T>
struct foo
{
// as if the compiler did this:
typedef foo<T> foo; // (of course, actually illegal)
};
foo
在 foo<T>
范围内可用作为foo<T>
.不过,在范围解析运算符之后,该范围可供使用,并且模板参数是可选的。
关于c++ - 方法定义期间返回类型中所需的模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5149119/