尝试从私有实例调用模板方法时编译器错误

Ste*_*fan 3 c++ templates compiler-errors

(如果你已经知道答案,这个问题只是另一个问题的重复!)

(请注意我的后续问题:如果存在具有相同名称的不相关全局模板函数,为什么不需要模板关键字?)

当我尝试使用这种结构编译模板化的C++代码时,在指定的行中出现编译器错误:

template <int N>
struct A {
    template <int i>
    void f() {};
};

template <int N>
struct B {
    A<N> a;

    B(A<N>& a) : a(a) {}

    void test() {
        a.f<1>();  // does not compile
    }
};

int main() {
    A<2> a;
    a.f<1>();   // works fine
    B<2> b(a);
    b.test();
}
Run Code Online (Sandbox Code Playgroud)

g++ 说:

test2.cpp: In member function ‘void B<N>::test()’:
test2.cpp:14: error: expected primary-expression before ‘)’ token
test2.cpp: In member function ‘void B<N>::test() [with int N = 2]’:
test2.cpp:22:   instantiated from here
test2.cpp:14: error: invalid operands of types ‘<unresolved overloaded function type>’ and ‘int’ to binary ‘operator<’
Run Code Online (Sandbox Code Playgroud)

clang++ 说:

test2.cpp:14:16: error: expected expression
        a.f<1>();  // does not compile
           ^
1 error generated.
Run Code Online (Sandbox Code Playgroud)

相同的表达式在模板化的上下文中有效main(),但不在test()模板化类的方法中,模板化的类B具有A作为私有变量的实例.我很无能为什么这不起作用.

Iva*_*iev 5

你必须在a.template f<1>();里面使用b.test().

  • 这就是为什么C++是如此美妙的语言!我有点知道答案,但仍然无法随意提出 - 我认为`模板'将在a之前而不是在它之后.黑魔法,这 - 我在十年的练习中从未需要它. (2认同)