C++ 的解释将 `T const &&t` 与 `int const *` 匹配时的模板函数参数推导
我不明白在这种情况下参数推导规则是如何工作的。我有以下简单的代码片段:
template<typename T>
void fn(T const &&t) {
std::cout << __PRETTY_FUNCTION__ << std::endl;
std::cout << typeid(decltype(t)).name() << std::endl;
}
int main() {
int const *ar = nullptr;
std::cout << typeid(ar).name() << std::endl;
fn(std::move(ar));
}
我得到的结果如下:
PKi
void fn(const T &&) [T = const int *]
PKi
我不明白的是为什么 T
被推断为 const int *
。为什么 const
没有获得模式匹配?
I don't understand how the argument deduction rule works in this case. I have the following simple code snippet:
template<typename T>
void fn(T const &&t) {
std::cout << __PRETTY_FUNCTION__ << std::endl;
std::cout << typeid(decltype(t)).name() << std::endl;
}
int main() {
int const *ar = nullptr;
std::cout << typeid(ar).name() << std::endl;
fn(std::move(ar));
}
The result I get is as follows:
PKi
void fn(const T &&) [T = const int *]
PKi
What I don't understand is why T
is inferred as const int *
. Why the const
did not get pattern matched?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在参数声明
T const &&t
中,const
在T
上被限定,即声明了t
作为 const T 的右值引用。当传递
const int *
类型的ar
时,T
被推导为const int *
,然后t
将是const int * const &&
,即对const
指针的右值引用,该指针指向const int
。请注意,const 在不同的事物(不同级别)上进行限定,一个用于指针,一个用于指针接收者。In the parameter declaration
T const &&t
,const
is qualified onT
, i.e.t
is declared as an rvalue-reference toconst T
.When
ar
with typeconst int *
is passed,T
is deduced asconst int *
, then the type oft
would beconst int * const &&
, i.e. an rvalue-reference toconst
pointer toconst int
. Note that theconst
s are qualified on different things (on different levels), one for the pointer, one for the pointee.