C++模板 t 不是有效的模板类型

C++ template t is not valid template type

本文关键字:类型 有效 模板 C++      更新时间:2023-10-16

我的.h文件:

template <typename T>
class UpdateUtils
{
public:
typedef struct {
QList<T> file;
} TPath;
static TPath *getIdealPath(QList<TPath *> &paths);
};

我的.cpp文件:

template <typename T>
TPath *UpdateUtils<T>::getIdealPath(QList<TPath *> &paths) {
return 0;
}

这会在 cpp 文件中产生错误:

error: C2143: syntax error : missing ';' before '*'
error: C2065: 'T' : undeclared identifier
error: C2923: 'UpdateUtils' : 'T' is not a valid template type argument for parameter 'T'

如果我TPath *返回类型替换为例如int,它有效。你能指教吗?

TPathUpdateUtils内部定义的嵌套类,您应该对其进行限定并使用typename关键字。

template <typename T>
typename UpdateUtils<T>::TPath *UpdateUtils<T>::getIdealPath(QList<TPath *> &paths)
^^^^^^^^^^^^^^^^^^^^^^^^^

或者按照建议@PiotrSkotnicki应用尾随返回类型:

template <typename T>
auto UpdateUtils<T>::getIdealPath(QList<TPath *> &paths) -> TPath *
^^^^                                                     ^^^^^^^^^^

请注意,对于类定义之外的成员函数定义,将在类范围内查找参数列表和尾随返回类型中使用的名称,因此您无需限定它们(不过可以限定它们(。这不适用于返回类型。[basic.scope.class]/4

扩展到类定义末尾

或超过类定义末尾的声明的潜在范围也会扩展到其成员定义定义的区域,即使成员在类外部以词法方式定义(这包括静态数据成员定义、嵌套类定义和成员函数定义,包括成员函数体和此类定义中此类定义中遵循声明符 id 的任何部分, 包括参数声明子句和任何默认参数(。