Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

partial template specialization for friend classes?

I have a simple class X, and set of templatized classes Y<T,U>. I'd like all classes Y where the first templatization parameter happens to be X to be a friend of X itself. The following hopefully conveys what I want, but the friend statement gives a compile error.

template<typename T, typename U>
class Y {
};

class X {
    public:
        X(int value) : i(value) {}
        const int& getI()    const { return i; }
    private:
        int    i;
        template<class U> friend class Y<X,U>;
};

I'm not sure templatization of friend statements is allowed at all (let alone partial templatization of friend statements). Is there a way to do this? Or am I stuck listing out all the friends one-by-one?

Thanks, Matt

like image 325
Matthew Busche Avatar asked May 27 '17 06:05

Matthew Busche


Video Answer


2 Answers

The friend declaration page on cppreference.com specifies:

Friend declarations cannot refer to partial specializations, but can refer to full specializations

So as chtz said you can have a non-partial specialization friend.

Edit:

See also another answer on stackoverflow: https://stackoverflow.com/a/11046918/5776353

like image 139
Pierre Avatar answered Oct 07 '22 11:10

Pierre


For the non-partial part of your question, the syntax is:

class X {
    template<class T, class U> friend class Y;
};

I guess, in most cases that should be sufficient.


With C++11 you can actually friend a templated alias:

template<typename T, typename U>
class Y { };

class X {
    public:
        X(int value) : i(value) {}
        const int& getI()    const { return i; }
    private:
        int    i;
        template<class U> using YX = Y<X,U>;
        template<class U> friend class YX;
};

However, that does not seem to work (I'm not sure if the friend declaration above has any effect at all).

like image 6
chtz Avatar answered Oct 07 '22 12:10

chtz