C++ 链接语义动作
我无法链接语义操作 我想解析一个百分比(C++ 链接语义动作,c++,parsing,c++17,boost-spirit-x3,C++,Parsing,C++17,Boost Spirit X3,我无法链接语义操作 我想解析一个百分比(X%和X实数),并将其值作为介于0和1之间的浮点值返回。如果百分比高于100%,我也希望失败 我目前拥有的是两个几乎微不足道的简单规则和一些简单的语义动作: const auto ensure_normalized = [](auto& context) { const auto& value = _attr(context); _pass(context) = value >= 0 && value <
X%
和X
实数),并将其值作为介于0和1之间的浮点值返回。如果百分比高于100%,我也希望失败
我目前拥有的是两个几乎微不足道的简单规则和一些简单的语义动作:
const auto ensure_normalized = [](auto& context)
{
const auto& value = _attr(context);
_pass(context) = value >= 0 && value <= 1;
_val(context) = _attr(context);
};
template<typename T, typename ContextType>
void multiply_by(T multiplier, ContextType& context)
{
using value_type = std::remove_reference_t<decltype(_val(context))>;
using attribute_type = std::remove_reference_t<decltype(_attr(context))>;
_val(context) = value_type(_attr(context) * attribute_type(multiplier));
}
constexpr auto divide_by_100 = [](auto& context) { multiply_by(.01f, context); };
const auto percentage = rule<struct percentage, float>{"percentage"}
= (float_ >> '%')[divide_by_100];
const auto normalized_percentage = rule<struct normalized_percentage, float>{"normalized_percentage"}
= percentage[ensure_normalized];
我得到一个垃圾值。看来sure_normalized
中的赋值也有点像黑客。我只是不知道如何告诉X3该做什么
代码已打开。如果代码按预期工作,将是发布问题的更合适的站点…(float)“%”,[divide_by_100][divide_by_100][divide_by_100]
也不工作。lambda被调用了3次,但只有第一次调用它时才有任何效果。看起来您只能为\u val(上下文)
分配一次。我认为现在最好的解决方案是增加一个规则包装器。
const auto normalized_percentage = rule<struct normalized_percentage, float>{"normalized_percentage"}
= ((float_ >> '%')[divide_by_100])[ensure_normalized];