Is there a way to specify that all classes in the Variadic parameter package are friends of the template to use operator =?

I saw a solution .

This is what I would like to have:

template <typename... F> struct A { protected: A& operator=(const SomeClass &other) { //... } private: //I would like to do the following, but it does not work friend F...; } 

Is there a way to do what I need?

+7
c ++ c ++ 11 friend templates variadic-templates
source share
1 answer

Well, you can always play dirty. First define a repeat macro:

 #define REPEAT_2(M, N) M(N) M(N+1) #define REPEAT_4(M, N) REPEAT_2 (M, N) REPEAT_2(M, N+2) #define REPEAT_8(M, N) REPEAT_4 (M, N) REPEAT_4(M, N+4) #define REPEAT_16(M, N) REPEAT_8 (M, N) REPEAT_8(M, N+8) #define REPEAT_32(M, N) REPEAT_16 (M, N) REPEAT_16(M, N+16) #define REPEAT_64(M, N) REPEAT_32 (M, N) REPEAT_32(M, N+32) #define REPEAT_128(M, N) REPEAT_64 (M, N) REPEAT_64(M, N+64) 

Then put 128 friend announcements in the variation class template of your choice:

 template <typename... T> class A { #define FRIEND(N) friend std::tuple_element_t< std::min((std::size_t)N+1, sizeof...(T)), std::tuple<void, T...>>; REPEAT_128(FRIEND, 0) static constexpr int i = 3; }; struct X; struct Y; struct Z; using ASpec = A<X, Y, Z>; struct X {int i = ASpec::i;}; struct Y {int i = ASpec::i;}; struct Z {int i = ASpec::i;}; template class A<>; // Small test for empty pack 

Demo Subscribe to @dyp.

If you have access to Boost.Preprocessor, all of this can be written much more succinctly using BOOST_PP_REPEAT .

+4
source share

All Articles