Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template Reference Collapsing Dropping cv-qualifiers for const Reference Return Type

I have this very general wrapper class

template<typename T>
class Raw
{
    T obj;

public:
    Raw() {};
    Raw(const T& init): obj(init) {};

    T& get() {return obj;};
    const T& get() const {return obj;};
};

This class is actually part of polymorphic hierarchy of other classes involving overriding get function, but I'm isolating this one class for my question.

So for regular non-reference types of T, this works as wanted. My original plan was to have a separate class Reference<T> which did the same thing except it was constructed and managed a reference type.

However, this class given a T& value, would do just that, thanks to handy dandy reference collapsing. The const would be dropped in the constructor as per the standard, as well as collapse down to a T& as desired.

The only seeming issue with the interface is the return type of the cv-qualified get function. In this case I don't want the const to be dropped since internals shouldn't be mutable in this case, however I believe according to the standard, the const Would be dropped.

Is there a work around for this or a way to explicitly tell the compiler what signature I want for that type. I know I can partially specialize, but that would entail a great deal of coupling for the rest of the class which I can almost avoid except for this small detail. Perhaps there is something meta-programmy I can do?

like image 339
bathtub Avatar asked Jun 03 '26 12:06

bathtub


1 Answers

You could use std::remove_reference to drop the reference and add it back:

#include <type_traits>

template<typename T>
class Raw
{
    T obj;
    using NR = std::remove_reference_t<T>;

public:
    Raw() {};
    Raw(const T& init): obj(init) {};

    NR& get() {return obj;};
    const NR& get() const {return obj;};
};
like image 116
Barry Avatar answered Jun 06 '26 06:06

Barry