尝试从私有实例调用模板方法时的编译器错误 [英] Compiler error when trying to call template method from private instance

查看:90
本文介绍了尝试从私有实例调用模板方法时的编译器错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

(This question is only a duplicate of the other question if you already know the answer!)

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

(Please note my follow-up question: Why is no template keyword needed if an unrelated global template function with same name exists?)

当我尝试使用此结构编译模板化C ++代码时, p>

I get a compiler error at the indicated line when I try to compile templated C++ code with this structure:

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(),但不在模板类 B test()方法中, code> A 作为私有变量。

The same expression works in the context of main(), but not within the test() method of the templated class B, which has an instance of A as a private variable. I am pretty clueless why this doesn't work.

推荐答案

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

这篇关于尝试从私有实例调用模板方法时的编译器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆