A specific operator instance for a specific operator

I have a class template and an operator template that needs to access its private field. I can make a template friend:

template <typename T>
class A {
    int x;
    template <typename U>
    friend bool operator==(const A<U>& a, const A<U>& b);
};

template <typename T>
bool operator== (const A<T>& a, const A<T>& b) {
    return a.x == b.x;
}

int main() {
    A<int> x, y;
    x == y;
    return 0;
}

But is it possible to make only a operator==<T>friend for A<T>and not make a operator==<int>friend A<double>?

+4
source share
2 answers

If you are having trouble with friend, forward the declaration before the class is defined A.

template <typename T>
bool operator== (const A<T>& a, const A<T>& b);

Then you can frienddo it more clearly. Complete solution ( ideone ):

template <typename T>
class A;

// declare operator== early (requires that A be introduced above)
template <typename T>
bool operator== (const A<T>& a, const A<T>& b);

// define A
template <typename T>
class A { 
    int x;
    // friend the <T> instantiation
    friend bool operator==<T>(const A<T>& a, const A<T>& b);
};

// define operator==
template <typename T>
bool operator== (const A<T>& a, const A<T>& b) { 
    return a.x == b.x;
}
+6
source

Yes, you can. The syntax is as follows:

template <typename T>
class A {
    int x;
    friend bool operator==<>(const A& a, const A& b);
};

operator== ( ) A.

+2

All Articles