I have a enum class which is used to clearly store the kinds of tokens which are passed into a parser for a calculator. The enum class looks like this:
enum class TokenKind
{
Number,
WhiteSpace,
Parenthesis,
Multiplication,
Divition,
Plus,
Minus,
Name
};
Using the scope specifier ::
to access the enum types of TokenKind works great for the most part. But I have a single syntax checking method which gets very unreadable having to use the scope specifier every time.
For only this method it would be more readable to use something like:
bool Parser::validSyntax(const std::vector<Token> tokens)
{
using namespace TokenKind;
{
const TokenKind firstKind = tokens.begin()->getKind();
const TokenKind lastKind = (tokens.end() - 1)->getKind();
switch(firstKind)
{
case Plus: case Divition:
case Multplication:
return false;
}
switch(lastKind)
{
case Plus: case Minus:
case Divition: case Multiplication:
return false;
}
}
for (auto it = tokens.begin(); it < tokens.end() - 1; ++it)
{
const TokenKind kind = it->getKind();
const TokenKind nextKind = std::next(it)->getKind();
switch(kind)
{
case Plus: case Minus:
case Divition: case Multiplication:
if (nextKind != Number && nextKind != Name && nextKind != Minus) return false;
case Number: case Name:
if (nextKind != Plus && nextKind != Minus &&
nextKind != Divition && nextKind != Multiplication) return false;
}
}
return true;
}
But using namespace ClassName;
is not valid syntax. Is there another way to achieve the behavior I am looking for? I am still quite new to C++ and have not nearly discovered all its functionalities.
C++20 introduced the using enum
directive that allows you to import the names of the specified enumeration into the scope.
In your case you would change
using namespace TokenKind;
to
using enum TokenKind;