C++14 中的 C++17 折叠表达式有什么好的替代方案吗?

2023-11-21

这是 C++17 中基于 lambda 的漂亮、简洁的折叠表达式:

#include <cstdint>

using ::std::uint64_t;

constexpr auto sumsquares = [](auto... n) { return ((n * n) + ...); };

// I want this to work.
uint64_t foo(uint64_t x, uint64_t y, uint64_t z)
{
    return sumsquares(x, y, z);
}
// And this too
double bar(uint64_t x, double y)
{
    return sumsquares(x, y);
}

我编写了这段代码,用于在 C++14 中执行类似的操作,但它似乎比应有的更加冗长和令人困惑。我正在寻找一种方法,以相对清晰和简洁的方式在 C++14 中表达上述 C++17 代码。准确地说,我希望能够编写代码,使用类似函数调用的语法来计算某个已知维数的向量的向量大小的平方。但维度的数量可以任意变化。并且坐标系的各个分量的精确数字类型也可以是任意的并且可能是异构的。但在 C++14 中处理 C++17 折叠表达式的通用方法将是理想的。

#include <cstdint>
#include <utility> 

using ::std::uint64_t;

namespace {
    static constexpr struct {
        template <typename T>
        auto operator()(T && n) const
        {
           return n*n;
        }
        template <typename T, typename... S>
        auto operator()(T && n, S && ... s) const
        {
            return (n * n) + (*this)(::std::forward<S>(s)...);
        }
    } sumsquares;
}

// I want this to work.
uint64_t foo(uint64_t x, uint64_t y, uint64_t z)
{
    return sumsquares(x, y, z);
}
// And this too
double bar(uint64_t x, double y)
{
    return sumsquares(x, y);
}

#include <utility>
#include <functional>

template<class F, class A0>
auto fold(F&&, A0&& a0) {
    return std::forward<A0>(a0);
}

template<class F, class A0, class...As>
auto fold(F&& f, A0&&a0, As&&...as) {
    return f(std::forward<A0>(a0), fold(f, std::forward<As>(as)...));
}

auto sum_squares=[](auto&&...args) {
    return fold(std::plus<>{}, (args * args)... );
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C++14 中的 C++17 折叠表达式有什么好的替代方案吗? 的相关文章

随机推荐