Skip to content

Latest commit

 

History

History
89 lines (63 loc) · 1.78 KB

352.md

File metadata and controls

89 lines (63 loc) · 1.78 KB
Info

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));

https://godbolt.org/z/Te8zzEoPd

Puzzle

  • Can you extend MyClass so that all Ts... will have access to privateData?
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));

https://godbolt.org/z/81dn33e41

Solutions

template <class... Ts>
class MyClass {
   friend Ts...;

   public:
    constexpr explicit MyClass(int data) : privateData(data) {}

   private:
    int privateData{};
};

https://godbolt.org/z/noradhE18