C++ 编译器将模板语法视为'<'运算符

c++ compiler treats template syntax as '<' operator

本文关键字:lt 运算符 编译器 语法 C++      更新时间:2023-10-16

我正在尝试编译以下代码:

struct A {
    template<int N> static void a() {}
};
template<> void A::a<5>() {}
template<class T>
struct B {
    static void b() {
        T::a<5>();
    }
};
void test() {
    A::a<5>();
    B<A>::b();
}

,编译器将T::a<5>中的<解释为操作符<,导致错误:

invalid operands of types ‘<unresolved overloaded function type>’ and ‘int’ to binary ‘operator<’

是否有任何方法显式实例化T::a<5>没有编译错误?谢谢你。

gcc version 4.5.1 20100924 (Red Hat 4.5.1-4) (gcc)

是,将这一行改为:

T::template a<5>();

编译器不知道T::a是否是一个函数(因为它的template性质)。通过提到template,您显式地通知编译器。这个问题被问了很多次,下面是其中一个。