Skip to content

Instantly share code, notes, and snippets.

@flomnes
Created August 23, 2024 13:26
Show Gist options
  • Save flomnes/ae78a5b0358ce0c3ee5d50b949acca29 to your computer and use it in GitHub Desktop.
Save flomnes/ae78a5b0358ce0c3ee5d50b949acca29 to your computer and use it in GitHub Desktop.
Exception throw in visitors
#include <stdexcept>
class IName
{
public:
virtual const std::string& name() const = 0;
};
class EqualNode: public IName
{
public:
const std::string& name() const override
{
static std::string name("EqualNode");
return name;
}
};
class NotImplemented: public std::invalid_argument
{
public:
NotImplemented(const IName& visitor, const IName& node):
std::invalid_argument("Visitor `" + visitor.name() + "` not implemented for node type `"
+ node.name() + "`")
{
}
};
class EvalVisitor: public IName
{
public:
const std::string& name() const override
{
static std::string name("EvalVisitor");
return name;
}
double visit(const EqualNode& node)
{
throw NotImplemented(*this, node);
}
};
#include <iostream>
int main()
{
EvalVisitor visitor;
EqualNode node;
try
{
visitor.visit(node);
}
catch (const NotImplemented& ex)
{
std::cout << ex.what() << std::endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment