【问题标题】:Why dependent template name accepted without keyword?为什么接受不带关键字的依赖模板名称?
【发布时间】:2016-09-17 22:22:49
【问题描述】:

我写了一个模板entry_func,它使用了一个模板类的模板方法func。在entry_func,要调用func,我应该使用关键字template。在示例中,第 (1) 行没有编译,第 (2) 行可以编译。到目前为止还可以。

但是,如果我稍微更改第 (1) 行并获得第 (3) 行,则第 (3) 行也会编译,而没有关键字 template。为什么?在我的理解中,这个变化应该不会影响关键字的需要。

#include <type_traits>

template<class>
struct Impl {
  template<class T>
  static T func(T t) {
    static_assert(sizeof(T)>=0, "Shouldn't be instantiated.");
  }
};

template<>
struct Impl<std::is_pointer<int*>> {
  template<class T>
  static T func(T u) {
    return u;
  }
};

template<class T>
inline T entry_func(T u) {
//return Impl<std::is_pointer<T  >>::func<T>(u);          // (1) fail
//return Impl<std::is_pointer<T  >>::template func<T>(u); // (2) ok
  return Impl<std::is_pointer<int>>::func<T>(u);          // (3) ok???
}

int main() {}

g++ 版本 5.3.1,clang 版本 3.8.0。

【问题讨论】:

    标签: c++ templates c++11 language-lawyer


    【解决方案1】:

    Impl&lt;std::is_pointer&lt;int&gt;&gt;::func in (3) 不是entry_func 中的从属名称。
    因此,func 是模板函数这一事实可以在没有 template 关键字的情况下轻松解决。
    请注意,在这种情况下,您使用 T 专门化 Impl&lt;std::is_pointer&lt;int&gt;&gt;::func 而不是 Impl&lt;std::is_pointer&lt;int&gt;&gt;,就像您在 (1)/(2) 中所做的那样。这是解读两种情况差异的关键。

    【讨论】:

      猜你喜欢
      • 2018-03-13
      • 2021-10-18
      • 1970-01-01
      • 2012-07-27
      • 2012-06-07
      • 1970-01-01
      • 1970-01-01
      • 2021-09-04
      相关资源
      最近更新 更多