在C ++ 14中,此C ++ 17折叠表达式的一个好的替代方法是什么? [英] What is a good alternative to this C++17 fold expression in C++14?

查看:102
本文介绍了在C ++ 14中,此C ++ 17折叠表达式的一个好的替代方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是C ++ 17中基于lambda的简洁明了的表达式:

Here is a nice, succinct fold expression based lambda in C++17:

#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折叠表达式的一般方法是理想的。

I have this code I've written to do something similar in C++14, but it seems a lot more verbose and confusing than it should be. I'm looking for a way to express the above C++17 code in C++14 in a way that's relatively clear and succinct. To be precise, I want to be able to write code that computes the square of the magnitude of a vector for a vector of some known number of dimensions with a function-call like syntax. The number of dimensions may vary arbitrarily though. And the precise numeric type of the individual components of the coordinate system may also be arbitrary and possibly heterogeneous. But a general way to handle C++17 fold expressions in C++14 would be ideal.

#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)... );
};

这篇关于在C ++ 14中,此C ++ 17折叠表达式的一个好的替代方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆