C++ Logo

std-proposals

Advanced search

Re: [std-proposals] How should we tag a class? Use an empty base class or a typedef?

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Tue, 28 May 2024 11:43:00 +0100
On Tue, May 28, 2024 at 12:48 AM Arthur O'Dwyer wrote:
>
> You have to re-opt-in to `is_library3_thing` at each level
> of inheritance (that is, at each leaf)


I think there are two kinds of tag you would want to put on a class:

    (1) Hereditary
    (2) Terminal

With hereditary tags, a derived class must opt out.
With terminal tags, a derived class must opt in.

And so a hereditary tag system would work like:

    class MyClass {
    public:
        typedef std::true_type tag_elide;
    };

And a terminal tag system would work like:

    class MyClass {
    public:
        typedef MyClass tag_elide;
    };

But instead of using typedef's for this purpose, should we instead be
talking about adding "Class Tagging" to C++26? It would work as
follows:

    class MyClass1 {
    public:
        tag [elide] hereditary;
    };

    class MyClass2 {
    public:
        tag [elide, some_other_tag] terminal;
    };

And then instead of creating a separate concept to use as a
constraint, you would just do:

    template<typename T, typename R> requires tagged[elide, some_other_tag]<T,R>
    void Func(void)
    {
        // Both T and R must have the tags "elide" and "some_other_tag"
    }

If we take it a step further, the core language could then even
interact with tags that the programmer has put on their own custom
classes. So for example, let's say we name a tag "no_local" and we put
it on our class "MyClass" as follows:

    class MyClass {
    public:
        tag [no_local] hereditary;
    };

And then we try to make a local variable:

    int main(void)
    {
        MyClass obj; // compiler error -- cannot make on the stack

        MyClass *p = new MyClass; // This is okay
    }

This would be a neat way of making sure massive classes don't get
allocated on the stack.

I'm sure there's a hundred other uses for this.

Received on 2024-05-28 10:43:14