模板类朋友函数的内部类

问题描述 投票:3回答:2

我有一个模板类A与内部类B。我想要一个朋友==运营商。但是,以下代码无法编译。它说,couldn't deduce template parameter ‘T’

#include <iostream>

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

        template<typename T2>
        friend bool operator == (const typename A<T2>::B& b1, const typename A<T2>::B& b2);
    };

    B b;
};

template<typename T>
bool operator == (const typename A<T>::B& b1, const typename A<T>::B& b2)
{
    return b1.b == b2.b;
}

int main() {
    A<int>::B b1, b2;
    b1.b = 3;
    b2.b = 2;

    std::cout << (b1 == b2) << std::endl;

    return 0;
}

我必须拥有朋友版本,因为其中一个STL算法调用它导致==没有找到,否则即使我有bool operator == (const B& b_) { return b == b_.b; }

解决这个问题的方法是什么?

c++ templates inner-classes
2个回答
3
投票

这是一个non-deduced context

表面上你可以有一个像这样的定义

template<typename AB>
bool operator == (const AB& b1, const AB& b2)
{
    return b1.b == b2.b;
}

但是它太过宽泛,因为它捕获了所有类型。 Yoiy可以这样限制它

template<typename AB>
auto operator == (const AB& b1, const AB& b2) ->
     std::enable_if_t<std::is_same_v<AB, typename A<decltype(b1.b)>::B>, bool>
{
    return b1.b == b2.b;
}

1
投票

这对我有用。

#include <iostream>

template<typename T>
struct A
{
    struct B
    {
        T b;
    };

    friend bool operator==(const typename A<T>::B &b1, const typename A<T>::B &b2)
    {
        return b1.b == b2.b;
    }

    B b;
};

int main() {
    A<int>::B b1, b2;
    b1.b = 3;
    b2.b = 2;

    std::cout << (b1 == b2) << std::endl;

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.