C++ Logo

std-discussion

Advanced search

A Idea: Friend with Conditions

From: SD SH <Z5515zwy_at_[hidden]>
Date: Sat, 21 Jun 2025 10:15:04 +0000
How about adding conditions for friend?
Like this (or other?):

class B { };
class E
{
    int i;
    E(int i) : i(i) { }
};
class A
{
    static int i = 0;
    friend typename T if(std::is_base_of<B, T>::value); // if a class derived from B, it is a friend class of A
    friend E if(std::is_default_constructible<E>::value); // E is not a friend class of A because std::is_default_constructible<E>::value == false
};
class C : B
{
public:
    int geti()
    {
        return A::i; // OK, because std::is_base_of<B, C>::value == true
    }
};
class D
{
public:
    int geti()
    {
        return A::i; // Error, because std::is_base_of<B, D>::value == false
    }
};

A Probably Syntax:
    friend <type-id> if/*constexpr*/(<constexpr-bool-expression>);

It may be a useful syntax feature.

E. S. Himers
2025/06

Received on 2025-06-21 10:15:13