c++ - 为什么在函数模板的前向引用上没有选择重载?
问题描述
片段:
#include <iostream>
template<typename T>
struct Printer{};
template<typename T>
void test(T&&)
{
std::cout << "Primary template called\n";
}
template<typename T>
void test(Printer<T>&&)
{
std::cout << "Specialized template called\n";
}
int main()
{
auto t = Printer<int>{};
test(0);
test(t);
}
这是演示
Primary template called
为什么要打印两次?
如果从第二个模板中删除前向引用,则Printer
选择重载。
为什么不选择 with &&
?
解决方案
转发参考仅适用于T&&
,不C<T>&&
适用const T&&
。
test(0); // Call test(T&&) with T=int
test(t); // Call test(T&&) with T=Printer<int>&
推荐阅读
- mysql - 如何提高 MySQL 转储恢复的性能
- node.js - 温斯顿自定义日志颜色
- python - 在 tkinter 中使用按钮,将某个变量传递给其余代码并关闭窗口
- python - 如何让我的函数找到我的excel表?
- google-apps-script - 搜索和替换不记录在谷歌表格中
- mysql - 按结果集对组进行排名
- java - Spring Security - 授权服务器的主体与资源服务器不同
- php - 如何在协议 PHP 中为一次交互提供几个端点?
- angular - 将 NGRX 与 Angular 服务相结合
- python - Python - 数据框 - 无法删除重复项