Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Friend specific template instantiation of operator

Tags:

c++

friend

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 operator==<T> friend for A<T> and not making operator==<int> friend of A<double> ?

like image 750
RiaD Avatar asked Feb 07 '23 00:02

RiaD


1 Answers

If having trouble with friend, then bring the declaration forward, before the A class is defined.

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

Then you can friend it more clearly. Full 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;
}
like image 80
Aaron McDaid Avatar answered Feb 20 '23 12:02

Aaron McDaid