C++:使用折叠表达式实现“多米诺骨牌更新”

问题描述 投票:0回答:2

考虑以下代码:

#include <iostream>
#include <functional>

template<class Val, class P>
void dominoe_update(P, Val&) {}

template<class Val, class Lval, class... More, class P>
void dominoe_update(P p, Val&& val, Lval& lval, More&... more)
{
    if (p(val, lval)) {
        lval = val; // No need to forward since it'd potentialy chain more copies anyway
        dominoe_update(p, val, more...);
    }
}

int main(int, char**)
{
    int i = 8, j = 9, k = 1;
    dominoe_update(std::less{}, 2, i, j, k);
    std::cout << i << ' ' << j << ' ' << k << '\n'; // Prints 2 2 1
    return 0;
}

dominoe_update
使用
val
更新所有参数,直到
p
返回
false

是否可以使用折叠表达式来实现上述函数以删除递归并删除基本情况函数?我认为这是不可能的,因为短路逻辑。

c++ c++17 variadic-templates
2个回答
2
投票

这是一种方法:

template <class P, class Val, class... Lvals>
void dominoe_update(P p, Val&& val, Lvals&&... lval) {
    ((/*if*/        p(val, lval)
      /*then*/      && (lval = val, true))
      /*and next*/  && ...);
}

演示


1
投票

接受挑战。

template<typename P, typename Val, typename... Lval>
void dominoe_update(P p, Val&& val, Lval&... lval)
{
    bool go = true;
    ( (go && (go = p(val, lval)) ? (void(lval = val), 0) : 0), ...);
}

演示

© www.soinside.com 2019 - 2024. All rights reserved.