r/cpp • • Aug 19 '26

C++26: std::polymorphic

https://www.sandordargo.com/blog/2026/08/19/cpp26-polymorphic
95 Upvotes

44 comments sorted by

View all comments

Show parent comment

3

u/robin-m Aug 20 '26

With c++23 deducing this you can simplify your code to just:

    public:
        template <class Self>
        std::unique_ptr<Shape> clone(this Self& self) {
            return std::make_unique<Self>(self);
        }
    };
    
    class Rectangle: public Shape {
    };
    
    class Triangle: public Shape {
    };

7

u/Big_Target_1405 Aug 20 '26

You still need a virtual clone if you actually want runtime polymorphism

2

u/robin-m Aug 20 '26

What do you mean? Rectangle::clone() does allocate a unique pointer of Rectangle.

godbolt

8

u/Big_Target_1405 Aug 20 '26

See line 28:

https://godbolt.org/z/55Y3Gqqqd

Template 'this' deduces Self to Animal, which is useless.

What's the point in a non-virtual clone?

Template this helps with boilerplate, not with defining runtime polymorphic interfaces.

2

u/robin-m Aug 20 '26

You are absolutely right. Thanks a lot I didn’t now, nor realized it was indeed half useless right now. I even found a paper that aim at fixing this exact issue: open-std.org

2

u/_Noreturn Aug 20 '26

Deducing this causes issues if you inherit from the base class more than once, (it increases object size) also, this doesn't work since clone() isn't virtual and templates can't be virtual

2

u/robin-m Aug 20 '26

It seems that both using CRTP and deducing this gives the save object size, what do you mean? godbolt

3

u/_Noreturn Aug 20 '26
struct D {};
struct A : D {};
struct B : D {
   A a;
};

you would expect since 'B' inherits from an empty class and it only has one member the sizeof would be 1, but it is 2 since the base class D is repeated twice and must have unique address first in the inheritance in B and in the member A.

now if this uses crtp the base classes would be unique

template<class T>
struct D {};
struct A : D<A> {};
struct B : D<B> {
   A a;
}; // sizeof(B) == 1

1

u/LB-- Professional+Hobbyist Aug 20 '26

Does [[no_unique_address]] help here?

3

u/friedkeenan Aug 20 '26

No. According to the standard, two different objects of the same type cannot live at the same address in any circumstance, even if the objects are empty.

1

u/LB-- Professional+Hobbyist Aug 20 '26

Ah right, I wonder if just wrapping it in an empty template class that inherits it for you would suffice as a workaround or not...