C++ - 单个参数包可以在单个表达式中多次展开吗?

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

我有一个函数,它需要 3 个模板参数:两种类型和一个整数常量(用于特征存储要求)。它看起来像下面的模板:

template <typename In, typename Out, Eigen::StorageOptions Options>
void my_big_function(/* 3 Eigen parameters depending on template args... */) {
    /* Eigen::StorageOptions can also be an integer constant. */
    /* Do stuff with matrices... */
}

由于这个函数需要使用多个模板“三元组”绑定到python,我认为这可能是模板参数包的一个很好的使用。

我想实现以下目标:

// binds to python :
// - my_big_function<float, int, ColMajor>(...)
bind_my_big_function<float, int, Eigen::ColMajor>(m); // (1)
// binds to python :
// - my_big_function<float, int, ColMajor>(...)
// - my_big_function<float, int, RowMajor>(...)
// - my_big_function<double, int, RowMajor>(...)
bind_my_big_function<float, int, Eigen::ColMajor, float, int, Eigen::RowMajor, double, int, Eigen::RowMajor>(m); // (2)

其中

bind_my_big_function
足够简单:

template <typename MatIn, typename MatOut, Eigen::StorageOptions MatOptions, typename...RemainingArgs>
void bind_my_big_function(pybind11::module_& m) {
    /* bind function taking MatIn, MatOut, MatOptions and go onto binding other variants of my_big_function */
}

虽然我肯定可以生成一些处理情况 (1) 的代码,但我无法弄清楚如何编写处理情况 (2) 的代码。我得到的最接近的是这样的:

template <
    typename MatIn, typename MatOut, Eigen::StorageOptions MatOptions
>
void bind_my_big_function(pybind11::module_& m) {
    m.def("my_big_function_in_python", &my_big_function<MatIn, MatOut, MatOptions>, /* python arguments...*/);
}

template <
    typename MatIn, typename MatOut, Eigen::StorageOptions MatOptions,
    typename...RemainingArgs, typename = typename std::enable_if_t<sizeof...(RemainingArgs) != 0>
>
void bind_my_big_function(pybind11::module_& m) {
    m.def("my_big_function_in_python", &my_big_function<MatIn, MatOut, MatOptions>, /* python arguments...*/);
    bind_my_big_function<RemainingArgs...>(m);
}

参数包应该这样使用吗?我能找到的唯一使用它们的例子是:

  • 使用模板化函数参数,
  • 一次使用单个包扩展“使用”(被调用的函数仅需要一种类型和一个可变参数模板包)
c++ templates variadic-templates
1个回答
0
投票

不确定我是否理解这个问题,但是如果你想实例化一些给定的

foo<Ts...,Ts...,Ts...>
,你可以包装函数模板,只需实例化它:
Ts...

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