C++ 的解释将 `T const &&t` 与 `int const *` 匹配时的模板函数参数推导

发布于 2025-01-15 15:02:56 字数 575 浏览 4 评论 0原文

我不明白在这种情况下参数推导规则是如何工作的。我有以下简单的代码片段:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

℡Ms空城旧梦 2025-01-22 15:02:56

在参数声明T const &&t中,constT上被限定,即声明了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 on T, i.e. t is declared as an rvalue-reference to const T.

When ar with type const int * is passed, T is deduced as const int *, then the type of t would be const int * const &&, i.e. an rvalue-reference to const pointer to const int. Note that the consts are qualified on different things (on different levels), one for the pointer, one for the pointee.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文