使用整数作为模板参数时出现编译错误
下面这段代码有什么问题?
template<typename X>
struct A {
template<int N>
int foo() const {
return N;
}
};
template<typename X>
struct B {
int bar(const A<X>& v) {
return v.foo<13>();
}
};
#include <iostream>
using std::cout;
using std::endl;
int main() {
A<double> a;
B<double> b;
cout << b.bar(a) << endl;
return 0;
}
在函数 B::bar
内,编译器抱怨:
错误:类型的操作数无效 '' 和 'int' 到二进制 'operator<'
如果 A 不是模板,则一切都可以正常编译。
What is wrong with the following piece of code?
template<typename X>
struct A {
template<int N>
int foo() const {
return N;
}
};
template<typename X>
struct B {
int bar(const A<X>& v) {
return v.foo<13>();
}
};
#include <iostream>
using std::cout;
using std::endl;
int main() {
A<double> a;
B<double> b;
cout << b.bar(a) << endl;
return 0;
}
Inside the function B::bar
the compiler complains:
error: invalid operands of types
‘’ and ‘int’ to binary ‘operator<’
If A is not a template, everything compiles fine.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将
return v.foo<13>();
更改为return v.template foo<13>();
因为foo
是依赖名称并且您需要明确使用.template
构造来提及。Change
return v.foo<13>();
toreturn v.template foo<13>();
becausefoo
is a dependent name and you need to mention that explicitly using.template
construct.