如何分解向量并将其值用作函数的参数

How to explode a vector and use its values as the arguments of a function?

本文关键字:函数 参数 何分解 分解 向量      更新时间:2023-10-16

我目前正在做的是:

std::vector<sometype> myparams;
...
while (...)
  myparams.push_back(somevalue);
...
somefunction(myparams[0], myparams[1], myparams[2], otherargument);

我有很多函数的实现,接受 1 到 100 个参数。我无法更改某些函数,但是我想知道是否有一种更漂亮的方法来使用它,因此通过创建另一个函数/宏来更改 myparams 的大小,该函数/宏将接受向量作为参数并调用某个函数具有向量的所有值作为参数。

知道吗?

非常感谢。

好吧,你不应该真的这样做,但你来:)使用升压::p再处理器:

#include "stdafx.h"
#include <vector>
void somefunction(int p1)
    { std::cout << p1 << " " << std::endl;}
void somefunction(int p1, int p2) 
    { std::cout << p1 << " " << p2 << std::endl;}
void somefunction(int p1, int p2, int p3) 
    { std::cout << p1 << " " << p2 << " " << p3 << std::endl;}
void somefunction(int p1, int p2, int p3, int p4)
    { std::cout << p1 << " " << p2 << " " << p3 << " " << p4 << std::endl;}
#define MAX_ARGS 4
#include <boost/preprocessor/repetition.hpp>
void UnpackVector(const std::vector<int> &v)
{
    #define MACRO(z, n, _) 
    case n: somefunction(
    BOOST_PP_ENUM_BINARY_PARAMS(BOOST_PP_INC(n), v[,]BOOST_PP_INTERCEPT) 
    );break;
    switch(v.size() - 1)
    {
        BOOST_PP_REPEAT(MAX_ARGS, MACRO, nil)
    }
}
void Run()
{
    int v_[] = { 42, 41, 40, 39 };
    std::vector<int> v(v_, v_ + sizeof(v_) / sizeof(int));
    UnpackVector(v);
}

只是为了笑。

真的不可能。C++中的每个函数调用表达式都有固定数量的参数。因此,必须有 100 个函数调用表达式。即

switch (myparams.size()) {
  case 0: somefunction(); break;
  case 1: somefunction(myparams[0]); break;
  case 2: somefunction(myparams[0], myparams[1]); break;
  // etc.

为此,您可能需要使用加速预处理器。

如果一组参数经常一起使用,为什么不将它们存储在struct中,并在接受该结构的现有函数周围创建一个包装器呢?

你可以让某个函数接受一对迭代器; 这样你得到 0 ...无穷大参数都具有相同的签名。