【问题标题】:Why is "a.template foo<0>();" allowed even though "a.foo<0>();" is enough?为什么是“a.template foo<0>();”即使“a.foo<0>();”也允许足够的?
【发布时间】:2018-08-27 01:54:58
【问题描述】:
struct A
{
    template<int>
    void foo()
    {}
};

int main()
{
    A a;
    a.foo<0>(); // ok
    a.template foo<0>(); // also ok
}

显然,a.foo&lt;0&gt;();a.template foo&lt;0&gt;(); 更简洁、直观和富有表现力。

为什么 C++ 允许 a.template foo&lt;0&gt;();,即使 a.foo&lt;0&gt;(); 就足够了?

【问题讨论】:

  • 因为在某些情况下a.template foo&lt;0&gt; 是必需的,所以为什么不到处允许呢?
  • template&lt;typename T&gt; void do_stuff() { T a; a.template foo&lt;0&gt;(); } ... do_stuff&lt;A&gt;();
  • 不允许在此处使用将需要更复杂的语言语法。
  • 事实上,曾经有一段时间是不允许的。 C++11 放宽了简化语法的要求。用-std=c++03 -pedantic-errors 试试,你的编译器会抱怨你。

标签: c++ templates syntax standards member-functions


【解决方案1】:

有时,在模板中,您需要编写 a.template foo&lt;0&gt;() 而不是 a.foo&lt;0&gt;()

@melpomene 在 cmets 中给出了这个很好的例子:

template<typename T>
void do_stuff() {
  T a;
  a.template foo<0>();
}
do_stuff<A>();

  • 在 C++03 中,a.template foo&lt;0&gt;() 不应在您当前的情况下使用。

g++ 在编译代码时会输出以下警告:

警告:模板之外的“模板”关键字 [-Wc++11-extensions]

  • 在 C++11 中,语法得到了简化,允许在任何地方使用 a.template foo&lt;0&gt;() 语法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-22
    • 1970-01-01
    • 2022-11-21
    • 2021-11-26
    相关资源
    最近更新 更多