Home > Backend Development > C++ > How Can I Avoid Duplicate Getters for Const and Non-Const Member Functions in C ?

How Can I Avoid Duplicate Getters for Const and Non-Const Member Functions in C ?

Mary-Kate Olsen
Release: 2024-12-02 11:42:16
Original
332 people have browsed it

How Can I Avoid Duplicate Getters for Const and Non-Const Member Functions in C  ?

Elegant Solution to Duplicate Getters for Const and Non-Const Objects

When dealing with getters in C , developers often encounter the dilemma of having to create separate implementations for const and non-const versions. This can be inconvenient when the logic for both getters is largely similar.

One potential solution to this issue is to implement the non-const version by casting away the const from the const version. This approach is considered safe because the calling function is non-const, which implies that the object itself is non-const, allowing for the conversion.

For instance:

class Foo
{
public:
    const int& get() const
    {
        //non-trivial work
        return foo;
    }

    int& get()
    {
        return const_cast<int&>(const_cast<const Foo*>(this)->get());
    }
};
Copy after login

This approach may not be aesthetically pleasing, but it guarantees safety and avoids the need for separate implementations in many cases. It allows developers to focus on the core functionality of the getters rather than duplicating code.

The above is the detailed content of How Can I Avoid Duplicate Getters for Const and Non-Const Member Functions in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template