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

时间:2020-01-10 10:11:11

标签: c++ templates

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;,它将可以编译。

我不知道为什么。

1 个答案:

答案 0 :(得分:0)

使用

v. template m<int>();

根据C ++ 17标准(17.2模板专业名称)

4据说,关键字模板出现在 合格ID(如果它出现在templateargument-list之外)或 十进制类型说明符。在声明者ID的限定ID中或在 由类头名称(第12条)或枚举头名称组成的合格ID (10.2),关键字模板不得出现在顶层。在一个 qualified-id用作类型名称规范(17.6)中的名称, 详细类型说明符(10.1.7.3),使用声明(10.3.3)或 class-or-decltype(第13条),出现了一个可选的关键字模板 在顶层被忽略。在这些情况下,<标记始终是 假设要引入一个模板参数列表。 其他所有 上下文,当命名成员的模板特化时 未知专业化(17.6.2.1),成员模板名称应为 由关键字模板确定