[libcxx-dev] Providing custom template specialization for std::optional?

Louis Dionne via libcxx-dev libcxx-dev at lists.llvm.org
Mon Mar 11 08:39:50 PDT 2019



> On Mar 7, 2019, at 10:18, Владимир Гончаров via libcxx-dev <libcxx-dev at lists.llvm.org> wrote:
> 
>> Can you explain what your specialization does differently? And why it's needed?
> 
> 
> I have a class which is a C++ interface for an object defined in a C library. Internally, it is a pointer which can never be null (if C interface returns null, the class constructor throws).
> I want to use this fact to optimise optional's storage. That would allow shrinking optional's size to eight bytes. Since we store a lot of optionals of this class, this change would reduce memory usage by about five percent (I've done some testing).
> I really don't want to invent a new optional specifically for this case. I also don't want to allow storing null pointers inside of the original class because this would require an assert before almost any usage of the class.

I think the right thing to do here is to invent a new optional that works for any type that has an unused value (a sentinel value). Actually, I think somebody has done that already in the wild but I can't seem to find it right now.

> 
>> I think the standard is being too permissive here.
> 
> 
> Maybe it is. But again, if I can provide a more efficient specialization which would utilise some knowledge about the wrapped type, why shouldn't I?

The problem is that doing so will almost certainly screw up implementations. When we implement something, it's usually necessary to make assumptions about how all the specializations of a class are implemented, which we do abundantly. Allowing _arbitrary_ types to be specialized for user-defined types means that we can't assume anything anymore, and that's a significant burden on implementers.

Louis



More information about the libcxx-dev mailing list