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

How Can I Elegantly Handle Duplicate Getters in C ?

DDD
Release: 2024-12-07 19:43:12
Original
530 people have browsed it

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;
};
Copy after login

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;
};
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template