将数量可变的参数传递给函数

Pass a variable number of arguments into a function(将数量可变的参数传递给函数)

本文介绍了将数量可变的参数传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何使用可变模板和省略号接受可变数量的参数,但如何将可变数量的参数传递给函数?

以以下代码为例:

#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;

}

这篇关于将数量可变的参数传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:将数量可变的参数传递给函数

基础教程推荐