1

If I have a class which takes variadic pack of template arguments how can I declare them all to be friends?

Here is what I would like to do in pseudo-code form:

template<typename... Ts>
class AbstractMyClass {
    int privateInt;
    friend Ts...;
};
class OtherClass;
using MyClass = AbstractMyClass<OtherClass>;

class OtherClass {
public:
    void foo(MyClass &c){
        c.privateInt = 42;
    }
};
odinthenerd
  • 5,422
  • 1
  • 32
  • 61
  • 1
    A better idea than friending might be a [passkey](http://stackoverflow.com/a/3324984/500104) (the C++11 `allow` version). – Xeo Nov 24 '13 at 14:11

1 Answers1

-1

This can only be done using "compile time recursion", much like tuples. The gist is (I am on a small laptop right now and by no means able to comfortably type):

template<class .... THINGS> class object;

template<class T> class object {
    friend T;
};

template<class T,class ... THINGS>
class object: public object<THINGS> {
    friend T;
};

If C++ doesn't like that, try template<> class object<> {}; as the one that ends the recursion (I terminate it with an object in 1 template paramater)

(Thanks to Dietmar Kuhl for formatting)

Alec Teal
  • 5,770
  • 3
  • 23
  • 50
  • I think the termination case "template class object" needs to hold the formerly private section ('privateInt' in this case) as a protected member in order for all the friends to access it. Make that change and I will accept. – odinthenerd Nov 24 '13 at 11:47
  • This is so far removed from anything compilable that I felt compelled to downvote it six years later. – Peter Sep 25 '19 at 15:39
  • @Peter forgive my comments if you were just desperately copying and pasting and hoping for it to compile ;) – Alec Teal Sep 26 '19 at 17:28
  • Also @peter anyone who writes template class thing should be shot. – Alec Teal Sep 26 '19 at 17:28
  • Curiously my comment about @Peter 's awesome (it did inspire awe) to not understand "template class object {" when followed by one line/one statement, then "};" which was longer than the diff would be to produce those changes has somehow vanished. Good luck Peter. – Alec Teal Sep 27 '19 at 00:29