C++ 模板推导:常量引用和常量指针 模板 空隙f(T) {} int x=1; 常数int&rx=x; 常量int*px=&x; f(rx);//t是int f(px);//t是常数int*,而不是int*,为什么???
我现在很困惑。根据有效的现代c++ 重要的是要认识到,常量只会被值忽略 参数。如我们所见,对于引用-或的参数 指针指向const时,expr的constness在类型转换期间保留 扣除额 我想它的意思是C++ 模板推导:常量引用和常量指针 模板 空隙f(T) {} int x=1; 常数int&rx=x; 常量int*px=&x; f(rx);//t是int f(px);//t是常数int*,而不是int*,为什么???,c++,templates,pointers,reference,template-argument-deduction,C++,Templates,Pointers,Reference,Template Argument Deduction,我现在很困惑。根据有效的现代c++ 重要的是要认识到,常量只会被值忽略 参数。如我们所见,对于引用-或的参数 指针指向const时,expr的constness在类型转换期间保留 扣除额 我想它的意思是 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
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???
模板
空隙f(T*T)
{}
f(px);//t是常数int*
模板
空f(T&T)
{}
f(cx);//t是常数int&
模板
空隙f(T)
{}
f(值);//推导参数t的类型时,将忽略值的常量或volatile
所以我认为当上面的f(px)
时,t
应该是int*
,但事实上它是const int*
为什么引用的
const
会被忽略,而指针的const
不会被忽略?
或者,为什么不
rx
const int&
?只忽略顶级const/volatile限定符。所有其他的都是你这种类型的内在品质。换句话说,你正在复制一个指针——这意味着函数在一个副本上运行,对它的任何修改(比如分配另一个变量的地址)都不会修改原始指针。但是,如果将指针传递给const int,那么让函数修改整数是非常违反直觉的
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)在上面时,px应该是int*,但实际上它是常数int*
点是参数的类型,按值传递和按引用/指针传递的行为会发生变化
按值传递时,将忽略参数本身的常量。对于指针参数,指针的常量被忽略(const-pointer->pointer),但指针对象的常量仍然保留(pointer-to-const->pointer-to-const)
这是有意义的,因为当传递指针时,指针本身被复制,但指针对象是相同的,它们都指向相同的对象,所以指针对象的常量被保留;从调用者的角度来看,他们不希望修改对象,他们可能会在以后使用它。当传递一个引用(这里的引用实际上并不重要)时,您将得到一个全新的复制值,它与原始值无关,然后忽略常量
正如本书中的以下解释,当指向const(aconst char*const
)的const指针通过时
模板
无效f(T参数);//参数仍按值传递
const char*const ptr=//ptr是指向const对象的const指针
“指针的乐趣”;
f(ptr);//pass arg的类型为const char*const
为
param
推导的类型将是const char*
我很困惑,因为我认为引用的常量也应该保留。在我的示例中,我认为rx
应该是const int&
,而不是int
。我一直认为引用和指针是一样的。好吧,我错了。@Thomas区别在于,当你传递一个指针时,指针本身被复制,但指针对象是相同的,它们都指向同一个东西,所以指针对象的常量被保留。当你传递一个引用时,你会得到一个全新的复制值,它与原始值无关,然后constness被忽略。Re:“为什么rx
const int&
?”:如果你写f(rx)
(而f(rx)
,它可能是无效的)。但是,对于这个问题,您也可以编写f(x)
。因此,rx
的引用与模板参数推导无关;它被视为是一个常量int
。
template <typename T>
void f(T t)
{
t = &another_variable; // ok
}
f(px);
void f(T t)
{
*t = 42; // not ok!
}
f(px); // secretly modifying `x` through a pointer to 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