我有一个接收常量引用的函数,我需要使用此引用调用模板库函数:
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::d evice"作为"this"参数传递会丢弃限定符 [-permissive]
我无法更改 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
通过非 const 引用获取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
然而,看看图书馆的来源,我真的不明白为什么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也许是时候提交错误报告了?