使用整数作为模板参数时编译器出错。

3
以下代码有什么问题?
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’不能作为二进制运算符‘<’的操作数

如果A不是模板,则一切都可以正常编译。


2
可能是c++模板语法的重复问题。 - CB Bailey
1个回答

15

return v.foo<13>(); 改为 return v.template foo<13>();,因为 foo 是一个相关名称,你需要使用 .template 结构明确指出。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接