我试图为ints创建一个lookup表到boost::static_visitor。
using VariableValue = boost::variant<int, double, std::string>;
struct low_priority {};
struct high_priority : low_priority {};
struct Mul : boost::static_visitor < VariableValue>{
template <typename T, typename U>
auto operator() (high_priority, T a, U b) const -> decltype(VariableValue(a * b)) {
return a * b;
}
template <typename T, typename U>
VariableValue operator() (low_priority, T, U) const {
throw std::runtime_error("Incompatible arguments");
}
template <typename T, typename U>
VariableValue operator() (T a, U b) const {
return (*this)(high_priority{}, a, b);
}
};
const std::map < int, boost::static_visitor<VariableValue> > binopHelper = {
{1, Mul{}}
};
然而,当我进行以下操作时。
std::cout << (VariableValue)boost::apply_visitor(binopHelper.at(1), (VariableValue)2, (VariableValue)4) << std::endl;
我得到的错误信息是: term does not evaluate to a function taking 2 arguments (编译源文件interpreter. cpp)
term does not evaluate to a function taking 2 arguments (compiling source file interpreter.cpp)
如何让static_visitor接受两个参数,以匹配于 Mul
?
你会是 切片. 你需要动态分配。最快的方法是使用类型擦除。
诀窍是想出一个固定的静态已知原型。在这种情况下,一个二进制函数就是它,你可以在其中添加 apply_visitor
发往 Mul
对象。
#include <boost/variant.hpp>
#include <functional>
#include <iostream>
#include <map>
using VariableValue = boost::variant<int, double>;
struct Mul : boost::static_visitor<VariableValue> {
struct high_priority{};
struct low_priority{};
auto operator() (VariableValue const& a, VariableValue const& b) const {
return boost::apply_visitor(*this, a, b);
}
template <typename T, typename U>
auto operator() (high_priority, T a, U b) const -> decltype(VariableValue(a * b)) {
return a * b;
}
template <typename T, typename U>
VariableValue operator() (low_priority, T, U) const {
throw std::runtime_error("Incompatible arguments");
}
template <typename T, typename U>
VariableValue operator() (T a, U b) const {
return (*this)(high_priority{}, a, b);
}
};
const std::map < int, std::function<VariableValue(VariableValue const&, VariableValue const&)> > binopHelper = {
{1, Mul{}}
};
int main() {
VariableValue i(42), d(3.1415926);
std::cout << binopHelper.at(1)(i, d) << "\n";
std::cout << binopHelper.at(1)(d, i) << "\n";
}
印刷品。
131.947
131.947
看上去你正在实现表达式评估,你可以做得更简单一些,比如重新使用stadard库。你可以做得更简单,例如重新使用stadard库。我在这里有一个相当广泛的演示。https:/github.comseheqi-extended-parser-evaluatorblobmastereval.h#L360 在【SO】上开发的,在这里的聊天讨论中。https:/chat.stackoverflow.comtranscript2102892020325。
如果你想了解更多,可以问我任何问题。
具体来说,那里的代码展示了如何在适当的情况下处理类型错配和隐式bool转换。