c ++从模板参数解包参数包

pre*_*eys 4 c++ parameters pack

如何实现我想要下面的想要?我要解包的参数包不在函数参数列表中,而是在模板参数列表中.

#include <iostream>
#include <array>

const std::size_t SIZE = 10;

template <int...ARGS>
std::array<bool, SIZE> func() {
    std::array<bool, SIZE> b;
    // I want to set b[n] = true, where n takes on all values from ARGS...
    // what to put in here???
    return b;
}

// Example of what I want to achieve:
int main() {
    const std::array<bool, SIZE> b = func<1,3,7>();
    // I want b[1]==true, b[3]==true, b[7]==true, all others false
    for (int x: b) std::cout << x << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

我必须使用这个形式的func(而不是func(1,3,7))来让我的更大的程序工作(我正在处理多个继承问题).

Sam*_*all 9

递归模板解决方案:

// recursive helper struct
template <int n, int First, int ...Rest>
struct helper {
  static void funcImpl(std::array<bool, SIZE>& temp) {
    temp[First] = true;
    helper<n - 1, Rest...>::funcImpl(temp);
  }
};

// partial specialization to catch base case
template <int First>
struct helper<0, First> {
  static void funcImpl(std::array<bool, SIZE>& temp) {
    temp[First] = true;
  }
};

template <int ...Args>
std::array<bool, SIZE> func() {
    std::array<bool, SIZE> b = {}; // 0 inititalize array
    helper<sizeof...(Args) - 1, Args...>::funcImpl(b);
    return b;
}
Run Code Online (Sandbox Code Playgroud)

编辑:受iavr解决方案启发的超简化版本:

template <int... A>
std::array<bool, SIZE> func() {
    std::array<bool, SIZE> b = {};
    auto values = {A...};
    std::for_each(values.begin(), values.end(), [&](int n){b[n] = true;});
    return b;
}
Run Code Online (Sandbox Code Playgroud)

  • 最后的解决方案简直太漂亮了。 (2认同)

iav*_*avr 5

这是一个更简单的解决方案,不需要额外的东西,只需这样:

struct _do { template <typename... T> _do(T&&...) { } };

template <int... A>
std::array<bool, SIZE> func() {
    std::array<bool, SIZE> b = {};
    _do{b[A] = true...};
    return b;
}
Run Code Online (Sandbox Code Playgroud)

这假设首先初始化数组然后填充.我之前的解决方案在编译时计算了所有值,并直接用它们初始化了数组.因此编译速度可能更快,运行速度也更慢.