[英]Const correctness advice
我有一個接收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
通過非const引用獲取dev
(盡管這可能需要您在調用站點修改代碼),或者您自己first
重新實現。
只需更換
std::vector<cv::Size> get_resolutions(const rs2::device& dev)
同
std::vector<cv::Size> get_resolutions(rs2::device& dev)
但是,這也意味着您不能再使用臨時對象調用get_resolutions
。
然而,看看庫的來源 ,我真的不明白為什么first()
是非const的。 它所做的只是調用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可能是時候提交錯誤報告?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.