I have the following code:
template <typename T>
struct Val
{
T val;
const T& get() const { return val; }
void set(const T& newVal) { val = newVal; }
};
int& f(const Val<int>& val)
{
return val.get();
}
int* g(const Val<int*>& val)
{
return val.get();
}
int main()
{
Val<int> val1;
f(val1);
Val<int*> val2;
g(val2);
return 0;
}
It fails compilation in gcc with the following message:
main.cpp: In function 'int& f(const Val<int>&)':
main.cpp:78:20: error: invalid initialization of reference of type 'int&' from expression of type 'const int'
return val.get();
^
main.cpp:79:1: warning: control reaches end of non-void function [-Wreturn-type]
That's totally fine, but why isn't the same error produced for g()
? Why, for some reason, is the const qualifier removed on const T&
, when T
is a pointer?
I tried to find some resources, but it seems hard to find. I know Meyers wrote something in his newest book, but I don't have access to that one. Can someone point me to resources or keywords where I could find more on that whole topic of template type deduction when T
is a pointer?
Why, for some reason, is the const qualifier removed on const T&, when T is a pointer?
Because you're returning the pointer by value, not by reference. It is perfectly fine to initialize a pointer from a const pointer (note it is the pointers that are const
, not the things they point to.) You're doing the equivalent of this:
int* const p0 = nullptr; // const pointer
int* p1 = p0; // copy to non-const is OK
If you were to initialize a non-cost reference to poiter from a const pointer, you'd get a similar error to the first case:
// error: binding of reference to type 'int *'
// to a value of type 'int *const' drops qualifiers
int*& p1 = p;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.