Home >Backend Development >C++ >How Can I Elegantly Handle Duplicate Getters in C ?

How Can I Elegantly Handle Duplicate Getters in C ?

DDD
DDDOriginal
2024-12-07 19:43:12521browse

How Can I Elegantly Handle Duplicate Getters in C  ?

Addressing Duplicated Getters with Elegance

Encounters with redundant getter methods for duplicate, const, and non-const variables can be frustrating. Consider the example:

class Foobar {
public:
    Something& getSomething(int index);
    const Something& getSomething(int index) const;
};

Implementing either method with the other is impossible due to the inability to invoke the non-const version from the const method. A cast is necessary to call the const version from the non-const one.

A Practical Solution

While there is no perfect solution, one pragmatic approach is to implement the non-const version by casting away the const from the const version. Despite its simplicity, this method ensures safety. Since the calling member function is non-const, the object is also non-const, allowing the cast to be performed.

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

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

private:
    int foo;
};

By utilizing this approach, you can eliminate the need for duplicated getter methods and maintain the safety of your code.

The above is the detailed content of How Can I Elegantly Handle Duplicate Getters in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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