c++ - const 正确性建议
问题描述
我有一个接收 const 引用的函数,我需要使用此引用调用模板库函数:
std::vector<cv::Size> get_resolutions(const rs2::device& dev)
{
auto sensor = dev.first<rs2::depth_sensor>();
//more code
}
class device
{
public:
template<class T>
T first()
{
for (auto&& s : query_sensors())
{
if (auto t = s.as<T>()) return t;
}
throw rs2::error("Could not find requested sensor type!");
}
//more code
};
当我用 gcc 编译时,我得到这个错误:
错误:将 'const rs2::device' 作为 'this' 参数传递会丢弃限定符 [-fpermissive]
我无法更改 first() 函数,因为它是外部库的一部分(librealsense,此处的第 51 行)。我无法从函数参数 dev 中删除 const,因为这将导致在很多地方删除 const 正确性。
我可以通过从 dev 中删除 const 来克服错误:
auto sensor = const_cast<rs2::device&>(dev).first<rs2::depth_sensor>();
但是,这感觉不好。有没有更正确的方法来处理这个错误?我尝试了以下变体但未成功:
auto sensor = dev.first<const rs2::depth_sensor>();
auto sensor = const_cast<const rs2::depth_sensor>(dev.first<rs2::depth_sensor>());
但我和他们有同样的错误。
解决方案
我认为有两种可能的解决方案。您要么允许get_resolutions
通过dev
非常量引用(尽管这可能需要您在调用站点修改代码),要么您自己重新实现first
。
选项1
只需更换
std::vector<cv::Size> get_resolutions(const rs2::device& dev)
和
std::vector<cv::Size> get_resolutions(rs2::device& dev)
但是,这也意味着您不能再get_resolutions
使用临时对象进行调用。
选项 2
但是,查看library的源代码,我真的不明白为什么first()
是非常量。它所做的只是调用query_sensors()
(它是const 限定的,也是公共的),并处理结果:1
template<class T>
T first()
{
for (auto&& s : query_sensors())
{
if (auto t = s.as<T>()) return t;
}
throw rs2::error("Could not find requested sensor type!");
}
这可能是影响最小的选项:只需first()
在库外部定义一个复制此功能的您自己:
template <class T>
T custom_first(const rs2::device& dev)
{
for (auto&& s : dev.query_sensors())
if (auto t = s.as<T>())
return t;
throw rs2::error("Could not find requested sensor type!");
}
1是时候提交错误报告了,也许吧?
推荐阅读
- scala - 将带有标题的空 DF 写入 csv
- python - 如何通过 Python 连接到 Azure SQL Server
- fluentd - 流利的本地时间适用于标准输出,但不适用于弹性搜索
- ios - 如何在我的 iphone 上使用我的 IOS 应用程序而无需协同设计?
- azure - 如何在 ADF 中获取自纪元以来的毫秒数
- firebase - firebase firestore 读取如何计算?
- python - 如何使用python根据相关统计进行最佳分组?
- python - 不能将序列乘以“float”类型的非整数(没有库的图像混合)
- python - 返回作为第二个参数传递的数组中第一个参数的索引的函数
- amazon-web-services - AWS Cognito 在将 istio sidecar 添加到 pod 后无法进行身份验证