c++ - 对任意数量的可变参数应用函数

标签 c++ c++11 variadic-templates variadic-functions

这是 my previous one 的后续问题.我正在构建一个具有基本 vector 数学功能的数组类。我想定义一个函数,让用户将任意函数映射到整个数组。我已经可以为预定义的二进制函数执行此操作(例如,operator+= 用于就地添加),但我正在努力了解如何对任意数量的输入执行此操作。

template<typename T, size_t ... Ns>
class Array
{
public:
    Array() { /* allocate memory of size product(Ns) * sizeof(T) */ }

    ~Array() { /* deallocate memory */ }

    inline Array<T, Ns...>& operator+=(const Array<T, Ns...> &rhs)                   
    {
        // simple case: predefined operation on exactly two Arrays
        T *p1 = data, *p2 = rhs.data;                                                
        while (p1 != data + size) { *p1 += *p2; p1++; p2++; }                                                                            
        return *this;                                                                
    }

    template<class ... Args>
    inline const Array<T, Ns...> map(T (*fn)(arg_type<Args>...), Args ... args)
    {
        // difficult case: arbitrary operations on a variable number of Arrays
    }

    private:
        T *data;
        size_t size;
}

// example usage
double f(double a, double b) { return a + b; }
Array<double,2> x, y, z;
x.map(f, y, z);

我想要这样的东西来遍历 yz 中的所有元素,将 f 应用于它们,并将它们存储在 x。我想我可以在我的 operator+= 函数上对其建模,但我还没有找到可以让我做任何类似事情(和编译)的参数包扩展。

最佳答案

这样写:

template<class T, class Array2>
using Array_Size_Copy = // expression that creates a Array<T,???>, where ??? is the Ns... of Array2 above

然后

template<class F, class A0, class...Arrays>
auto array_apply( F&& f, A0&& a0, Arrays&&...arrays ) {
  using R = decay_t<decltype( f(std::declval<A0>().data.front(), std::declval<Arrays>().data.front()...) )>;

  Array_Size_Copy<R, std::decay_t<A0>> retval;

  for (int i = 0; i < a0.size(); ++i) {
    retval.data[i] = f( std::forward<A0>(a0).data[i], std::forward<Arrays>(arrays).data[i]... );
  }
  return retval;
}

添加一些断言(理想情况下是静态断言)所有内容的大小都相同。

以上功能可能需要加好友。这意味着您可能必须设置返回值而不是使用 auto,但这只是将类型体操移动到声明中。

关于c++ - 对任意数量的可变参数应用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36389046/

相关文章:

c++ - 从参数包中排除前 n 个参数

c++ - 使用 std::vector<std::future<int>> 和 std::async 启动几个线程时的 Abort()

c++ - AVL 树中的比较由指向对象的指针组成

c++ - 如何使用模板结构而不是函数检查容器的类型?

c++ - 将 std::list<std::unique_ptr> 移动到 vector 中尝试引用已删除的函数

c++ - 从 C++ 调用 Lua 函数

c++ - 在网格中的任何位置分布多个零

c++ - 动态对象的统一初始化

c++ - 这个可变参数模板代码有什么作用?

c++ - 使用可变参数模板创建哈希队列