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