我有以下代码:
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; }它使用以下消息在gcc中编译失败:
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]这完全没问题,但为什么g()产生的错误不一样? 出于某种原因,为什么在const T&上删除了const限定符,当T是指针时?
我试图找到一些资源,但似乎很难找到。 我知道迈耶斯在他最新的书中写了一些东西,但我无法访问那本书。 有人可以指向我的资源或关键字,当T是指针时,我可以在模板类型推导的整个主题上找到更多信息吗?
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?
最满意答案
出于某种原因,为什么在const T&上删除了const限定符,当T是指针时?
因为您按值返回指针,而不是通过引用。 从const指针初始化一个指针是完全没问题的(注意它是const的指针,而不是它们指向的东西。)你做的相当于:
int* const p0 = nullptr; // const pointer int* p1 = p0; // copy to non-const is OK如果你要从const指针初始化poiter的非成本引用,你会得到与第一种情况类似的错误:
// error: binding of reference to type 'int *' // to a value of type 'int *const' drops qualifiers int*& p1 = p;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 OKIf 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;更多推荐
发布评论