c++ - 带有 const ref 参数的函数模板特化
问题描述
以下代码编译良好。
#include <iostream>
struct rgb8{
uint8_t r() const {return 0;};
};
template<typename L, typename P>
L pixelToLevel(P p) {
return static_cast<L>(p);
}
template<>
uint8_t pixelToLevel<uint8_t, rgb8>(rgb8 p) { // <---------- line X
return pixelToLevel<uint8_t, uint8_t>(p.r());
}
int main()
{
pixelToLevel<uint8_t>(rgb8());
return 0;
}
但如果在第 XI 行更改rgb8 p
为const rgb8& p
,则编译失败。
(生成的确切编译器错误取决于显式模板参数rgb8
是否也更改为const rgb8&
。)
如果我想p
通过引用而不是 X 行的值传递,如何编译它?
解决方案
@songyuanyao 的另一种解决方案是
template<typename L, typename P>
L pixelToLevel(const P& p) {
return static_cast<L>(p);
}
推荐阅读
- random - 如何在没有 X 和硬件 RNG 的情况下填充内核熵?
- go - vscode 无法导入模块
- d3.js - d3 数据可视化中高度不同的值的正确比例是多少?
- python - Docker 防火墙 pip 安装错误
- python - 遍历文件夹和子文件夹?
- vba - 编译错误:在 .VBComponents("thisDocument").CodeModule.AddFromFile 之后 ActiveDocument.Close 预期结束子
- powershell - 将 guid 和路径作为变量传递给 bcdedit /set
- c# - Blazor 服务器:在 App.razor 中初始化的 Scoped 服务在 Page 中为空
- php - 在浏览器中查看 xlsx 文件:php
- r - 在 Shiny 应用程序中使用 Python Selenium 和 ChromeDriver