gpt4 book ai didi

c++ - 模板推导 : const reference and const pointer

转载 作者:太空狗 更新时间:2023-10-29 21:36:27 26 4
gpt4 key购买 nike

template <typename T>
void f(T t)
{}

int x = 1;
const int & rx = x;
const int * px = &x;
f(rx); // t is int
f(px); // t is const int *, instead of int *, WHY???

我现在很困惑。根据 Effective Modern c++

It’s important to recognize that const is ignored only for by-value parameters. As we’ve seen, for parameters that are references-to- or pointers-to-const, the constness of expr is preserved during type deduction.

我觉得是

template <typename T>
void f(T * t)
{}
f(px); // t is const int *

template <typename T>
void f(T & t)
{}
f(cx); // t is const int &

template <typename T>
void f(T t)
{}
f(value); // const or volatile of value will be ignored when the type of the parameter t is deduced

所以我觉得上面f(px)时,t应该是int *,但实际上是const int *.

为什么引用的const被忽略,而指针的const却没有?或者,为什么不是 rx const int &

最佳答案

So I think when f(px) above, px should be int *, but in fact it is const int *.

重点是参数的类型,按值传递按引用/指针传递的行为会发生变化。

当按值传递时,参数本身的常量性被忽略。对于指针参数,指针的常量性被忽略(const pointer -> pointer),但pointee的常量性仍然保留(pointer to const -> pointer to const)。

这确实有意义,因为当传递一个指针时,指针本身被复制,但指针对象是相同的,它们都指向同一事物,因此保留了指针对象的常量;从调用者的角度来看,他们不希望修改对象,他们可能会在以后使用它。当传递一个引用时(这里实际上引用并不重要),你会得到一个全新的值,与原来的值无关,然后constness被忽略。

如书中的以下解释,当const指向const(a const char* const)的指针传递时,

template<typename T>
void f(T param); // param is still passed by value

const char* const ptr = // ptr is const pointer to const object
"Fun with pointers";

f(ptr); // pass arg of type const char * const

param 推导的类型将是 const char*

关于c++ - 模板推导 : const reference and const pointer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40167411/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com