首页 > 解决方案 > 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>());

但我和他们有同样的错误。

标签: c++constants

解决方案


我认为有两种可能的解决方案。您要么允许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是时候提交错误报告了,也许吧?


推荐阅读