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

Dan*_*vil 7 c++ templates dependent-name

以下代码有什么问题?

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;
}
Run Code Online (Sandbox Code Playgroud)

在函数内部,B::bar编译器抱怨:

错误:类型''和'int'到二进制'operator <'的操作数无效

如果A不是模板,那么一切都很好.

Pra*_*rav 15

更改return v.foo<13>();return v.template foo<13>();因为foo是依赖名称,您需要明确使用.template构造.