c++ - 从一个值和一个大小创建递归函数参数列表

标签 c++ variadic-templates c++17 fold-expression

我的目的是创建一个大小为 n 的函数参数列表,以便我可以将其传递给使用折叠表达式以递归方式将这些值相乘的助手。

我对如何将参数列表传递给助手有点困惑。 有没有办法在没有包表达式的情况下创建函数参数列表? 也许通过创建数组或元组?

这是我到目前为止所想到的。

template<typename T, typename N>
T SmoothStart(const T& t, const N& n) {
    static_assert(std::is_integral_v<N>, "templatized SmoothStart requires type of N to be integral.");
    static_assert(n >= 0, "templatized SmoothStart requires value of N to be non-negative.");

    if constexpr (n == 0) {
        return 1;
    }
    if constexpr (n == 1) {
        return t;
    }
    return SmoothStart_helper((t, ...)); //<-- obviously this doesn't work but it would be awesome to have!
}

template<typename T, typename... Args>
T SmoothStart_helper(Args&&... args) {
    return (args * ...);
}

最佳答案

首先,n如果要使用折叠表达式,则必须在编译时知道。如果将其移至模板参数,则获得大小为 N 的参数包的最简单方法与 std::make_index_sequence :

// The helper has to be first so that the compiler can find SmoothStart_helper().
template<typename T, std::size_t... Is>
T SmoothStart_helper(const T& t, std::index_sequence<Is...>) {
    // You were taking t by value here; I think you might want to still
    // take it by reference

    // Use the comma operator to simply discard the current index and instead
    // yield t. The cast to void is to silence a compiler warning about
    // Is being unused
    return (((void) Is, t) * ...);
}

template<std::size_t N, typename T>
T SmoothStart(const T& t) {
    // std::size_t is unsigned, so no need to check for N >= 0.
    // We also don't need to special case when N == 1. The fold
    // expression handles that case and just returns t
    return SmoothStart_helper(t, std::make_index_sequence<N>{});
}

然后您可以像这样使用它:SmoothStart<N>(myThing); .

Godbolt

关于c++ - 从一个值和一个大小创建递归函数参数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48914265/

相关文章:

C++17 和静态临时生命周期的引用扩展

c++ - 从具有默认参数的类模板继承

c++ - 绘制 n 尖星 opengl c++

c++ - 每个具有自定义函数的编译时间

image - 将 3 channel 图像转换为 T 型单向量的最快方法

c++ - 是否可以在单行中获取第一种参数包?

c++ - 使用字符串和流头文件和函数将 c++ 代码转换为 arduino

c++ - Tcl_Interprer 为什么要这样实现呢?

c++ - 可变参数模板包扩展参数 id

c++ - Variadic 模板 - 如何创建存储传递参数的类型