Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

if template class<T> T=int&, why method set(const T val) !== set(const int& val)? const ignored why

T=int&, why .set(const T val) !== .set(const int& val)?

template <class T>
struct ClassA{
public:
    T data;                   // T == int&;
public:
    void set(const T val){    // T == int&;  why !== set(const int& val)
       this->data = val;
    }
};


void main(){
    int num = 1;
    ClassA<int&> instance {num};
    const int val = 100;
    instance.set(val);  // gcc error: binding reference of type 'int&' to 'const int' discards qualifiers
}

I don’t know what the rules on this site are; https://en.cppreference.com/w/cpp/language

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

[dcl.ref] … Cv-qualified references are ill-formed except when the
cv-qualifiers are introduced through the use of a typedef-name
([dcl.typedef], [temp.param]) or decltype-specifier
([dcl.type.simple]), in which case the cv-qualifiers are ignored

When T is a reference, like your int &, const T is also int &. The const is ignored.

You may have a reference to something that is const or volatile, but the reference itself cannot be const or volatile.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading