如何实现下面我想要的?我要解压的参数包不在函数参数列表中,而是在模板参数列表中。
#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;
}
我必须使用这种形式的 func (而不是 func(1,3,7))才能让我的更大的程序正常工作(我正在处理多重继承问题)。
递归模板解决方案:
// 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;
}
EDIT:受 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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)