【问题标题】:Compile error: unresolved overloaded function type编译错误:未解决的重载函数类型
【发布时间】:2013-03-19 14:21:04
【问题描述】:

我尝试使用 g++ 4.7.2 编译以下内容:

template <typename T>
struct A {
    struct B {
        T t;

        template<T B::*M>
        T get() {
            return this->*M;
        }
    };

    B b;

    T get() {
        return b.get<&B::t>();
    }
};


int main() {
    A<int> a;
    a.get();
}

它给了我

test.cpp: In member function ‘T A<T>::get()’:
test.cpp:15:23: error: expected primary-expression before ‘)’ token
test.cpp: In instantiation of ‘T A<T>::get() [with T = int]’:
test.cpp:22:8:   required from here
test.cpp:15:23: error: invalid operands of types ‘<unresolved overloaded function type>’ and ‘int A<int>::B::*’ to binary ‘operator<’

为什么?

谢谢。

【问题讨论】:

    标签: c++ templates compilation member-pointers


    【解决方案1】:

    您需要使用template 消歧器:

    return b.template get<&B::t>();
    

    没有它,解析表达式时:

    b.get<&B::t>();
    

    编译器无法判断它是否应该将get 解释为成员变量的名称后跟&lt; 符号(小于号),还是解释为名为@9​​87654327@ 的成员函数模板的实例化。

    虽然我们知道我们的表达式的预期含义是什么,但编译器不能,至少在实例化发生之前不能 - 并且即使您的函数从未实例化,也会执行句法解析。

    【讨论】:

    • 当你知道 C++ 的时候......我什么时候应该使用“模板消歧”? (我刚刚搜索过,但我似乎无法找到一个好的答案。)
    • @PaulDraper:实际上,我找到了this Q&A,这应该可以很好地解释它。
    • 优秀。这也包括对typename的解释,我也没有完全理解。
    • @PaulDraper:好的,很高兴它有帮助!
    猜你喜欢
    • 1970-01-01
    • 2013-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-23
    • 2013-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多