Created
August 23, 2024 13:26
-
-
Save flomnes/ae78a5b0358ce0c3ee5d50b949acca29 to your computer and use it in GitHub Desktop.
Exception throw in visitors
This file contains 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 <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