[英]Why am I getting the error “non-template 'f' used as template”
I'm trying to understand where to use template
and typename
and I came across a problem I can't quite get around. 我试图了解在哪里使用
template
和typename
,我遇到了一个我无法解决的问题。 I have a template-function f<T>
which uses the type passed to it (which will be a class) to call the template-member-function .f<T>
. 我有一个模板函数
f<T>
,它使用传递给它的类型(将是一个类)来调用template-member-function .f<T>
。 I think my use of typename
in the function body is correct, however, I keep getting the following error: 我认为我在函数体中使用
typename
是正确的,但是,我一直收到以下错误:
source.cpp: In function
'void f()'
:source.cpp:在函数
'void f()'
:
source.cpp:11:19: error: non-template'f'
used as templatesource.cpp:11:19:错误:非模板
'f'
用作模板
source.cpp:11:19: note: use'typename T::C::template f'
to indicate that it is a templatesource.cpp:11:19:注意:使用
'typename T::C::template f'
来表示它是一个模板
struct A {
struct C {
template <typename T> void f() {}
};
};
template <typename T> void f() {
typename T::C::f<int>();
}
int main() {
f<A>();
}
Notice how on the last error it advises to use 'typename T::C::template f'
instead. 注意如何在最后一个错误上建议使用
'typename T::C::template f'
。 So I made the following change in accordance: 所以我按照以下方式做了以下更改:
// ...
typename T::C::template f<int>();
// ...
I did as it said, but then I received the next line of error: 我按照说法做了,但后来收到了下一行错误:
error: no class template named
'f'
in'struct A::C'
错误:
'struct A::C'
没有名为'f'
类模板
I believe this error is incorrect in that there is in fact a public template function named f
in struct A::C
. 我相信,这个错误是不正确的,有其实名为公共模板函数
f
在struct A::C
。 What could I be doing wrong here? 我在这里做错了什么?
Assuming we make f
static
so it can be called without an instance, you don't need typename
because you're not creating any ambiguities with a dependent type (ie C
can't be a variable because you use it with ::
just after). 假设我们使
f
static
因此可以在没有实例的情况下调用它,因此您不需要使用typename
因为您不会使用依赖类型创建任何歧义(即C
不能是变量,因为您在::
just之后使用它)。 Here is the correct syntax: 这是正确的语法:
struct A {
struct C {
template <typename T>
static void f() {}
};
};
template <typename T> void f() {
T::C::template f<int>();
}
If you wanted not to make it static, you'd create a A::C
and use .template f<int>()
: 如果你不想让它静态,你可以创建一个
A::C
并使用.template f<int>()
:
struct A {
struct C {
template <typename T>
static void f() {}
};
};
template <typename T> void f() {
typename T::C c;
//^^^^^^^^ Now we DO need typename to disambiguate.
c.template f<int>();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.