Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/150.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么选择'<';as';操作员<';而不是将模板参数括起来的标记? 我的C++代码如下: //test.cpp #include <iostream> using namespace std; template <int SIZE, class T> struct A { void g(int x, const T& t) { t.f<SIZE>(x); } }; struct B { template <int SIZE> void f(int x) const { cout << SIZE << ": " << x << endl; } }; int main(void) { A<3, B> a; B b; a.g(9, b); return 0; }_C++_Templates - Fatal编程技术网

为什么选择'<';as';操作员<';而不是将模板参数括起来的标记? 我的C++代码如下: //test.cpp #include <iostream> using namespace std; template <int SIZE, class T> struct A { void g(int x, const T& t) { t.f<SIZE>(x); } }; struct B { template <int SIZE> void f(int x) const { cout << SIZE << ": " << x << endl; } }; int main(void) { A<3, B> a; B b; a.g(9, b); return 0; }

为什么选择'<';as';操作员<';而不是将模板参数括起来的标记? 我的C++代码如下: //test.cpp #include <iostream> using namespace std; template <int SIZE, class T> struct A { void g(int x, const T& t) { t.f<SIZE>(x); } }; struct B { template <int SIZE> void f(int x) const { cout << SIZE << ": " << x << endl; } }; int main(void) { A<3, B> a; B b; a.g(9, b); return 0; },c++,templates,C++,Templates,为什么需要,因为代码本身是模糊的,所以编译器必须决定哪种方式。而C++标准委员会任意决定,如果有疑问,假设名称是变量,而不是类型。< /P> 如果希望将代码解析为模板,则需要明确说明: t.template f<SIZE>(x); 如果现在使用该类型实例化A,则会得到(由于模板已实例化,因此为伪代码): void A::g(int x,T const&T){ ((t.f)x; } 我添加了括号来澄清:这是编译器如何看待代码的,它是完全有效的(尽管毫无意义)。让我们看看: t.f

为什么需要
,因为代码本身是模糊的,所以编译器必须决定哪种方式。而C++标准委员会任意决定,如果有疑问,假设名称是变量,而不是类型。< /P>
如果希望将代码解析为模板,则需要明确说明:

t.template f<SIZE>(x);
如果现在使用该类型实例化
A
,则会得到(由于模板已实例化,因此为伪代码):

void A::g(int x,T const&T){
((t.f)<3)>x;
}
我添加了括号来澄清:这是编译器如何看待代码的,它是完全有效的(尽管毫无意义)。

让我们看看:

t.f < SIZE > (x);
t.f(x);
空白并不重要。如果
t.f
是一个变量,那么可以这样说:Do
t.f
,然后Do(该结果)
>x

此外,编译器还不知道
t.f
是变量还是函数模板。请记住,模板可以专门化,所以即使现在看来
t.f
是一个函数模板;在这篇文章的后面,这个代码可以从
B
的专门化中实例化,其中
t.f
是一个变量


为了解决这个难题,不明确的名称将被视为变量名,除非您明确指出它们是其他名称。在这种情况下,通过编写
t.template f
;当
T
是一个从属名称时,类似的原则要求我们编写
typename T::iterator

一个很好的例子。谢谢。我认为t.f
是第一位的。@TonyK谢谢,修正了
struct T {
    int f;
};
void A<3, T>::g(int x, T const& t) {
    ((t.f) < 3) > x;
}
t.f < SIZE > (x);