c++ - 为什么通用引用必须对成员函数使用模板而不是类?
问题描述
例如:这不是通用参考:
template<typename T>
class C {
public:
void gogo(T&& c);
};
但这是:
template<typename A>
class C {
public:
template<typename B>
void gogo(B&& par);
}
解决方案
在第二个片段中,B&& par
不一定是通用参考。B
仅当您让编译器在调用时进行推断时,它才被认为是通用的:
C<float> c;
c.gogo(42); // T is deduced as int, `par` acts as an universal reference.
c.gogo<int>(42); // T is fixed, `par` is a regular rvalue reference.
由于在第一个代码段T
中,调用时总是固定的,所以引用永远不会通用。
C<int> c; // Must specify T here, there's no way for it to be deduced.
c.gogo(42); // T is fixed, `par` is a regular rvalue reference.
推荐阅读
- android - ImageViewHolder.getAdapterPosition() / .getLayoutPosition() 不起作用
- python - 为什么我的碰撞测试总是返回“真”,为什么图像矩形的位置总是错误 (0, 0)?
- python - 如何将正十进制 int 转换为十六进制字符串?
- java - 创建一个随机的,但在某个范围内最频繁的
- flutter - 如何实现异步 | 等待接收 geoLocation 包的距离?
- python - 压缩numpy浮点数组
- authentication - linux脚本中LDAP的用户认证测试
- python - 如何在 Python(Zeep 模块)中修复“'str'对象没有属性'keys'”?
- python - 用值更新字符串的最后一个字符
- powershell - Powershell GzipStream,“找不到“GZipStream”的重载和参数计数:“2”