其他分享
首页 > 其他分享> > c – 在“模板化基类”中调用模板方法时出错

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

作者:互联网

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

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

解决方法:

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

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

标签:generic-programming,c,templates,inheritance
来源: https://codeday.me/bug/20190902/1792088.html