在“模板化基类”中调用模板方法时出错

时间:2012-01-06 08:05:31

标签: c++ templates inheritance generic-programming

以下代码无法编译,为什么会这样?我该如何解决这个问题?

struct A{
    template<int N> int get() { return N; }
};

template <typename X>
struct B : public X {
    template<int N> int get() {
        return X::get<N>();
    }
};

int main(int argc, const char *argv[])
{
    B<A> b;
    return b.get<5>();
}

编译错误:

test.cxx: In member function ‘int B<X>::get()’:
test.cxx:8:30: error: expected primary-expression before ‘)’ token
test.cxx: In member function ‘int B<X>::get() [with int N = 5, X = A]’:
test.cxx:15:25:   instantiated from here
test.cxx:8:30: error: invalid operands of types ‘<unresolved overloaded function type>’ and ‘int’ to  binary ‘operator<’

1 个答案:

答案 0 :(得分:5)

你必须消除它的歧义,如下:

template<int N>int get() {
    return X::template get<N>();
}