Example
class FriendClass;
class MyClass {
friend class FriendClass;
public:
constexpr MyClass(int data) : privateData(data) {}
private:
int privateData;
};
struct FriendClass {
constexpr auto accessPrivateData(const MyClass& obj) const {
return obj.privateData;
}
};
constexpr MyClass obj{42};
constexpr FriendClass friend_obj{};
static_assert(42 == friend_obj.accessPrivateData(obj));
Puzzle
- Can you extend
MyClass
so that allTs...
will have access toprivateData
?
template<class... Ts>
class MyClass {
// TODO
public:
constexpr explicit MyClass(int data) : privateData(data) {}
private:
int privateData{};
};
template<auto>
struct FriendClass {
constexpr auto accessPrivateData(const auto& obj) const {
return obj.privateData;
}
};
constexpr MyClass<FriendClass<0>, FriendClass<1>, FriendClass<2>> obj{42};
constexpr FriendClass<0> friend_obj0{};
constexpr FriendClass<1> friend_obj1{};
constexpr FriendClass<2> friend_obj2{};
static_assert(42 == friend_obj0.accessPrivateData(obj));
static_assert(42 == friend_obj1.accessPrivateData(obj));
static_assert(42 == friend_obj2.accessPrivateData(obj));
Solutions
template <class... Ts>
class MyClass {
friend Ts...;
public:
constexpr explicit MyClass(int data) : privateData(data) {}
private:
int privateData{};
};