简体   繁体   中英

Inner class of a template class friend function

I have a templated class A with an inner class B . I want to have a friend == operator. However, the following code does not compile. It says, 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;
}

I have to have the friend version because the way one of the STL algorithms calls it results in == not found otherwise even if I have bool operator == (const B& b_) { return b == b_.b; } bool operator == (const B& b_) { return b == b_.b; }

What is the way to solve this?

It's a non-deduced context .

Ostensibly you could have a definition like

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

but it's too broad as it catches all types. Yoiy can restrict it this way

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;
}

This worked for me.

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM