lundi 20 avril 2015

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?

Aucun commentaire:

Enregistrer un commentaire