编译器错误 C7510
“type-name”:使用依赖模板名称必须带有“template”前缀
“type-name”:使用依赖类型名称必须带有“typename”前缀
在 /permissive-
模式下,当关键词在依赖 nested-name-specifier
之后,编译器要求 template
关键字在模板名称之前。 对 typename
限定的类型保留类似的规则。
备注
编译器行为已在 Visual Studio 2017 版本 15.8 /permissive-
模式下更改。 当关键词在依赖 nested-name-specifier
之后,编译器要求 template
或 typename
关键字在模板或者类型名称之前。 有关详细信息,请参阅依赖类型名称解析和模板和名称解析。
示例
在 /permissive-
模式下,以下代码现在会引发 C7510:
template<typename T> struct Base
{
template<class U> void example() {}
};
template<typename T>
struct X : Base<T>
{
void example()
{
Base<T>::example<int>(); // C7510: 'example': use of dependent
// template name must be prefixed with 'template'
// note: see reference to class template instantiation
// 'X<T>' being compiled
}
};
要修复此错误,将 template
关键字添加到 Base<T>::example<int>();
语句,如以下示例所示:
template<typename T> struct Base
{
template<class U> void example() {}
};
template<typename T>
struct X : Base<T>
{
void example()
{
// Add template keyword here:
Base<T>::template example<int>();
}
};
在 Visual Studio 2019 中的 /std:c++20
或更高版本下,具有 if constexpr
语句的函数模板正文启用了额外的与分析相关的检查。 例如,在 Visual Studio 2017 中,只有在 /permissive-
选项已设置时,以下代码才会生成 C7510。 在 Visual Studio 2019 中,即使设置了 /permissive
选项,相同的代码也会引发错误:
// C7510.cpp
// compile using: cl /EHsc /W4 /permissive /std:c++latest C7510.cpp
#include <iostream>
template <typename T>
int f()
{
T::Type a; // error C7510: 'Type': use of dependent type name must be prefixed with 'typename'
// To avoid the error, add the 'typename' keyword. Use this declaration instead:
// typename T::Type a;
if constexpr (a.val)
{
return 1;
}
else
{
return 2;
}
}
struct X
{
using Type = X;
constexpr static int val = 1;
};
int main()
{
std::cout << f<X>() << "\n";
}