Skip to content

Instantly share code, notes, and snippets.

@pvgoran
Last active January 13, 2026 18:47
Show Gist options
  • Select an option

  • Save pvgoran/68ffac213ec39fa175ed88c0feccce3a to your computer and use it in GitHub Desktop.

Select an option

Save pvgoran/68ffac213ec39fa175ed88c0feccce3a to your computer and use it in GitHub Desktop.
C++: Example of intentional member function hiding
#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