Link Pattern Collapsing Dropping cv-qualifiers for const Reference Return Type
I have this generic 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 a polymorphic hierarchy of other classes that include an overridden get function, but I am isolating this class for my question.
So, for regular non-basic types T, this works as desired. My original plan was to have a separate class Reference<T>
that did the same, except it was constructed and manipulated by a reference type.
However, this class, given the T & the value, will do just that, thanks to the handy dandy link collapses. const
will be discarded in the constructor as per the standard, and also collapsed to T & as desired.
The only apparent problem with the interface is the return type of the get-qual function. In this case, I don't want the const to be dropped since the internals shouldn't be mutable in this case, however, I suppose, according to the standard, const will be dropped.
Is there a work around for this, or a way to explicitly tell the compiler what signature I want for this type. I know I can specialize in part, but it will entail a lot of communication for the rest of the class that I will almost avoid, other than this little detail. Perhaps there is something meta-programming I can do?
source to share
You can use std::remove_reference
to remove the link 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;};
};
source to share