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

发布于 2024-09-18 12:23:14 字数 663 浏览 10 评论 0原文

下面这段代码有什么问题?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

哎呦我呸! 2024-09-25 12:23:14

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

Change return v.foo<13>(); to return v.template foo<13>(); because foo is a dependent name and you need to mention that explicitly using .template construct.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文