目录
最近看tensorflow的C++源码,发现一些难以理解的操作,如下图所示
不理解这里的 tensor.template 到底是什么意思(感觉C++用了挺多年了,这种写法倒是第一次见)
如果你懂了,请默默的关掉本页,如果你也有困扰,请接着往下看~
一.相关链接
经过多方搜索,终于找到一个能满足需求的答案,这里贴出链接
https://stackoverflow.com/questions/8463368/template-dot-template-construction-usage
如果你能看懂这个链接里面的内容,请摸摸的关掉本页,如果还有疑问,请接着往下看~
二. 问题的核心
问题的核心在于: .template 到底是什么意思?
下面列出一段测试代码(上面链接中的)
#include <iostream>
template <int N>
struct Collection {
int data[N];
Collection() {
for (int i = 0; i < N; ++i) {
data[i] = 0;
}
};
void SetValue(int v) {
for (int i = 0; i < N; ++i) {
data[i] = v;
}
};
template <int I>
int GetValue(void) const {
return data[I];
};
};
template <int N, int I>
void printElement(Collection<N> const& c) {
std::cout << c.template GetValue<I>() << std::endl; //1
std::cout << c. template GetValue<I>() << std::endl;//2
std::cout << c.GetValue<I>() << std::endl;//3, 这里也能编译通过
}
int main() {
Collection<10> myc;
myc.SetValue(5);
printElement<10, 2>(myc);
return 0;
}
printElement是一个模板函数,函数中调用形参 c的 GetValue<I> 函数的时候加了一个 .template 关键字,初次见到这种写法,以为是 c 里面有一个template函数。所以就各种百思不得其解。后来看到上述链接中的答案,才算彻底明白了。
三.问题的答案
对于上面的代码来说,GetValue 是一个依赖名(dependent name, 这个后面会再讲),因此需要明确的告诉编译器c后面跟的是一个函数模板,而不是成员变量,所以这里的 template 就是为了表明这里是函数模板。
另外,这里的 .template 并不是绑定在一起的一个符号,而是两个 ,即: .(dot) 和 template ,这里的template是与成员函数 GetValue绑定在一起的,而不是.(dot) , 这里的 . 是c 用来调用 GetValue 成员函数的(类似于普通的类变量访问成员函数的方法)。
四.关于依赖名的解释
请参考如下文章:
https://www.cnblogs.com/cthon/p/9201649.html
五.测试输出
编译上面的代码,发现1,2,3 均能编译通过(vs2015/vs2019)。 不存在他所说的 编译不过的情况。