不可能operator ==
按照您想要的方式制作版本。它不能变成静态的。如果它是一个成员,那么它必须有一个参数。
如果您愿意“复制代码”,那么您可以使用命名空间来玩花样。您的通用解释器可以是一个模板,它将特定语言的派生类作为模板参数。它反过来调用operator==
基于语言特定标记的模板。
template <typename TOKEN>
bool operator == (const std::string &l, const TOKEN token) {
return token == l;
}
// Language specific interpreters inherit from this template
template <typename LANG>
class Interpreter {
public:
void interpret () {
std::string s("hi");
if (s == LANG::KEYWORD_ELSE) {}
}
};
每个特定语言的子类都Interpreter
位于特定语言的命名空间中。该实现重复关键字的枚举,但在其他方面遵循模板实现。
namespace Lang0 {
class Interpreter : public ::Interpreter<Lang0::Interpreter> {
//...
public:
enum Token { KEYWORD_ELSE, //...
};
static Interpreter & instance () {
static Interpreter interpreter;
return interpreter;
}
};
}
namespace Lang1 {
class Interpreter : public ::Interpreter<Lang1::Interpreter> {
//...
public:
enum Token { KEYWORD_ELSE, //...
};
static Interpreter & instance () {
static Interpreter interpreter;
return interpreter;
}
};
}
每个命名空间还提供了一种特定于语言的实现,operator==
用于将字符串与特定于语言的标记进行比较。
namespace Lang0 {
bool operator == (const Interpreter::Token token, const std::string &l) {
//...
}
}
namespace Lang1 {
bool operator == (const Interpreter::Token token, const std::string &l) {
//...
}
}
然后,当 的模板实现Interpreter
调用 的模板版本时operator==
,它会解析为相应语言特定命名空间中的语言特定实现。