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

时间:2014-05-27 12:48:56

标签: c++ templates compiler-errors

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

(请注意我的后续问题:Why is no template keyword needed if an unrelated global template function with same name exists?

当我尝试使用这种结构编译模板化的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();
}

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<’

clang++说:

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

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

1 个答案:

答案 0 :(得分:5)

您必须在a.template f<1>();内使用b.test()