C++ Logo

std-discussion

Advanced search

回复: A Idea: Friend with Conditions

From: SD SH <Z5515zwy_at_[hidden]>
Date: Sat, 21 Jun 2025 12:55:26 +0000
I have another idea is that detached r/w permissions in class:
class A
{
public private: // r: public; w:private
    int i;
};

int main()
{
    A a;
    a.i; // OK
    a.i = 1; // Error
    // a.i is like <const int> there
}


Sure the existing way is also working:
public: // r&w: public
public private: // r: public; w: private
public public: // r: public; w: public

But it is hard to be in standard because getter functions are successful.
I don't know how do you think of it.
________________________________
发件人: Tiago Freire <tmiguelf_at_[hidden]>
发送时间: 2025年6月21日 18:53
收件人: std-discussion_at_[hidden] <std-discussion_at_[hidden]>
抄送: SD SH <Z5515zwy_at_[hidden]>
主题: Re: A Idea: Friend with Conditions

I think we need more development in this area. I certainly have use to make some interfaces public to some things but not others, without making everything public.
And better observability without compromise would also help in things like unit tests.
Making public to things that meet certain requirements is an interesting idea.

________________________________
From: Std-Discussion <std-discussion-bounces_at_[hidden]> on behalf of SD SH via Std-Discussion <std-discussion_at_[hidden]>
Sent: Saturday, June 21, 2025 12:15:18 PM
To: std-discussion_at_[hidden] <std-discussion_at_[hidden]>
Cc: SD SH <Z5515zwy_at_[hidden]>
Subject: [std-discussion] A Idea: Friend with Conditions

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 12:55:34