为什么在这种情况下我需要 .template

Why do I need .template in this case

本文关键字:template 这种情况下 为什么      更新时间:2023-10-16
template<typename T>
struct Obj
{
template<typename U>
void m(){};
};
template<typename T>
void func()
{
Obj<T> v;    // Obj<int> v; is compilable
v.m<int>();
}

这段代码给了我一个错误:

test.cpp: In function ‘void f()’:
test.cpp:21:9: error: expected primary-expression before ‘int’
v.m<int>();
^
test.cpp:21:9: error: expected ‘;’ before ‘int’

但是,如果我将Obj<T> v;更改为Obj<int> v;,它将是可编译的。

我不知道为什么。

使用

v. template m<int>();

来自 C++ 17 标准(17.2 模板专业化名称(

4 关键字模板据说出现在 限定 ID(如果它出现在模板参数列表之外(或 描述类型说明符。在声明符 id 的限定 id 中或在 由类头名(第 12 条(或枚举头名组成的限定 id (10.2(、关键字模板不得出现在顶层。在一个 限定 ID 用作类型名称说明符 (17.6( 中的名称, 详细类型说明符 (10.1.7.3(、使用声明 (10.3.3( 或 class-or-decltype(第 13 条(,出现一个可选的关键字模板 在顶层被忽略。在这些上下文中,<令牌始终>在所有其他 上下文,当命名模板时 未知特化(17.6.2.1(,成员模板名称应为 关键字模板为前缀