Search code examples
c++friend

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


Solution

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