c++ - 方法定义期间返回类型中所需的模板参数

标签 c++ templates

有谁知道为什么在定义模板方法时返回类型需要模板参数而不是参数类型?一个例子:

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 *,所以 CarCar<T> 的别名.但这只发生在 Car<T> 的范围内,这就是为什么你在其他任何地方都需要它,而不是在 :: 之后.当然,无论如何您都可以自己明确指定参数。


*这个特性最好这样解释:

template <typename T>
struct foo
{
    // as if the compiler did this:
    typedef foo<T> foo; // (of course, actually illegal)
};

foofoo<T> 范围内可用作为foo<T> .不过,在范围解析运算符之后,该范围可供使用,并且模板参数是可选的。

关于c++ - 方法定义期间返回类型中所需的模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5149119/

相关文章:

c++ - 为什么迭代时不能使用模板

结构散列的 C++ 无序集问题

c++ - 根据参数的积极性专门化模板

c++ - 类型别名是否用作函数签名的函数参数类型?

c++ - 如何触发 WSAOVERLAPPED 事件? (C++)

c++ - 将不同大小的 C 数组传递给采用 2 个相同参数的模板函数

c++ - 在 C++ 的另一个类中使用模板类

C++ 在模板声明中使用默认值

c++ - 使用变量值初始化静态有哪些运行时成本?

c++ - 在 WindowProc MFC 中使用 try/catch