简体   繁体   中英

Const correctness advice

I have a function that receives a const reference and I need to call a template library function using this reference:

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

};

When I compile with gcc I get this error:

error: passing 'const rs2::device' as 'this' argument discards qualifiers [-fpermissive]

I can't change the first() function as it's part of a external library (librealsense, line 51 in here ). I can't remove the const from the function argument dev because that will result in removing const correctness in a lot of places.

I can overcome the error by removing the const from dev:

auto sensor = const_cast<rs2::device&>(dev).first<rs2::depth_sensor>();

However, this feels bad practice. Is there any more correct way of dealing with this error? I have tried unsuccessfully the following variations:

auto sensor = dev.first<const rs2::depth_sensor>();
auto sensor = const_cast<const rs2::depth_sensor>(dev.first<rs2::depth_sensor>());

but I get the same error with them.

I think there are two possible solutions to this. Either you allow get_resolutions to take dev by non-const reference (although that may require you to modify code at the call site), or you re-implement first yourself.

Option 1

Just replace

std::vector<cv::Size> get_resolutions(const rs2::device& dev)

with

std::vector<cv::Size> get_resolutions(rs2::device& dev)

This, however, would also mean that you can no longer call get_resolutions with a temporary object.

Option 2

Looking at the source of the library , however, I really can't see why first() is non-const. All it does is call query_sensors() (which is const-qualified, and also public), and process the results: 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!");
}

This might be the option with the lowest impact: Just define a first() yourself, outside of the library, that replicates this functionality:

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 Time to file a bug report, maybe?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM