c++ - 为什么接受没有关键字的依赖模板名称?

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

我写了一个模板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。

最佳答案

Impl<std::is_pointer<int>>::func(3) 中不是entry_func 中的从属名称.
正因为如此,func是一个模板函数,无需 template 即可轻松解析关键词。
请注意,在这种情况下,您使用的是 T专业Impl<std::is_pointer<int>>::func而不是 Impl<std::is_pointer<int>> ,就像您在(1)/(2) 中所做的那样。这是阅读这两种情况之间差异的关键。

关于c++ - 为什么接受没有关键字的依赖模板名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39552259/

相关文章:

c++ - 使用 SSE 的矩阵乘法

C++ 顶点缓冲区问题

c++ - 从 std::array 获取对原始数组的引用

c++ - 隐式转换 : const reference vs non-const reference vs non-reference

c++ - `type_info::before` 有什么用?

c++ - 需要引用标准关于 main 函数作为模板函数的合法性

javascript - 问题使用 Mustache 模板渲染 Backbone 集合

c++ - 为什么不能推导嵌套在模板类中的枚举的模板参数?

c++ - 将 nullptr 传递给可变模板指针

c++ - 对象容器的性能与指针容器的性能