我知道如何使用可变模板和省略号来接受可变数量的参数,但如何将变量数量的参数传递到函数中?
以以下代码为例:
#include <iostream>
struct A {
A(int a, int b) : x(a), y(b) {}
int x, y;
};
struct B {
B(int a, int b, int c) : x(a), y(b), z(c) {}
int x, y, z;
};
template<typename T, typename... TArgs>
T* createElement(TArgs&&... MArgs) {
T* element = new T(std::forward<TArgs>(MArgs)...);
return element;
}
int main() {
int Aargs[] = { 1, 2 };
int Bargs[] = { 1, 2, 3 };
A* a = createElement<A>(Aargs); //ERROR
B* b = createElement<B>(Bargs); //ERROR
std::cout << "a.x: " << a->x << "na.y: " << a->y << "n" << std::endl;
std::cout << "b.x: " << b->x << "nb.y: " << b->y << "nb.z: " << b->z << "n" << std::endl;
delete a;
delete b;
}
有没有任何方法可以扩展数组,使它们的每个值都像一个传递给函数的参数(类似于参数包扩展(?
或者,如果没有,还有其他方法可以让它发挥作用吗?
您可以使用std::index_sequence
扩展阵列
#include <iostream>
#include <utility>
struct A {
A(int a, int b) : x(a), y(b) {}
int x, y;
};
struct B {
B(int a, int b, int c) : x(a), y(b), z(c) {}
int x, y, z;
};
template<typename T, typename... TArgs>
T* createElement(TArgs&&... MArgs) {
T* element = new T(std::forward<TArgs>(MArgs)...);
return element;
}
template<typename T, typename U, size_t... I>
T* createElementFromArrayHelper(std::index_sequence<I...>, U* a){
return createElement<T>(a[I]...);
}
template<typename T, typename U, size_t N>
T* createElementFromArray(U (&a)[N]){
return createElementFromArrayHelper<T>(std::make_index_sequence<N>{}, a);
}
int main() {
int Aargs[] = { 1, 2 };
int Bargs[] = { 1, 2, 3 };
A* a = createElementFromArray<A>(Aargs);
B* b = createElementFromArray<B>(Bargs);
std::cout << "a.x: " << a->x << "na.y: " << a->y << "n" << std::endl;
std::cout << "b.x: " << b->x << "nb.y: " << b->y << "nb.z: " << b->z << "n" << std::endl;
delete a;
delete b;
}