Last active
January 13, 2026 18:47
-
-
Save pvgoran/68ffac213ec39fa175ed88c0feccce3a to your computer and use it in GitHub Desktop.
C++: Example of intentional member function hiding
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <string> | |
| #include <iostream> | |
| #pragma GCC diagnostic warning "-Woverloaded-virtual" | |
| struct Visitor | |
| { | |
| virtual void visit(int val) const =0; | |
| virtual void visit(std::string const &val) const =0; | |
| }; | |
| template<class Derived> | |
| struct GenericVisitor : Visitor | |
| { | |
| virtual void visit(int val) const override | |
| { | |
| self().visit(val); | |
| } | |
| virtual void visit(std::string const &val) const override | |
| { | |
| self().visit(val); | |
| } | |
| private: | |
| Derived const &self() const | |
| { | |
| return static_cast<Derived const&>(*this); | |
| } | |
| }; | |
| template<class Overloads> | |
| struct OverloadVisitor : GenericVisitor<OverloadVisitor<Overloads>>, Overloads | |
| { | |
| explicit OverloadVisitor(Overloads overloads) | |
| : GenericVisitor<OverloadVisitor>(), Overloads(std::move(overloads)) | |
| { | |
| } | |
| template<class T> | |
| void visit(T&& val) const | |
| { | |
| this->operator()(std::forward<T>(val)); | |
| } | |
| // Adding the following (which is suggested in the GCC manual) to silence | |
| // the warning does not work, both with 'private:' and without it. | |
| // With 'private:' the compiler complains about inaccessible members, | |
| // and without 'private:' the code compiles but crashes due to infinite | |
| // recursion. | |
| //private: | |
| // using GenericVisitor<OverloadVisitor<Overloads>>::visit; | |
| }; | |
| void acceptVisitor(const Visitor &visitor) | |
| { | |
| visitor.visit(42); | |
| visitor.visit("This was the answer."); | |
| } | |
| int main() | |
| { | |
| std::cout << "Hello cruel world!" << std::endl; | |
| OverloadVisitor visitor([](auto &&val) { | |
| std::cout << "Logging: " << val << std::endl; | |
| }); | |
| acceptVisitor(visitor); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment