将数量可变的参数传递给函数
我知道如何使用可变模板和省略号接受可变数量的参数,但如何将可变数量的参数传递给函数?
以以下代码为例:
#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 << "
a.y: " << a->y << "
" << std::endl;
std::cout << "b.x: " << b->x << "
b.y: " << b->y << "
b.z: " << b->z << "
" << 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 << "
a.y: " << a->y << "
" << std::endl;
std::cout << "b.x: " << b->x << "
b.y: " << b->y << "
b.z: " << b->z << "
" << std::endl;
delete a;
delete b;
}
相关文章