如何分解向量并将其值用作函数的参数
How to explode a vector and use its values as the arguments of a function?
我目前正在做的是:
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 ...无穷大参数都具有相同的签名。
相关文章:
- static_assert在宏中,但也可以扩展到可以用作函数参数的东西
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 当从函数参数中的临时值调用复制构造函数时
- 如何从"decltype()"获取函数参数的数量<funtion>?
- 如何将lambda作为模板类的成员函数参数
- 模板参数推导失败,函数参数/参数不匹配
- 如何在C++中将迭代器作为函数参数传递
- 将函数参数"const char*"转换为"std::string_view"是
- C++ 如何将数组值解压缩为函数参数
- 主函数参数的属性
- 具有两个间接寻址运算符 (C++) 的函数参数的用途
- "Warning: Comma within array index expression"但逗号分隔函数参数
- 如何定义在用作函数参数时工作的类模板的转换
- 将函数参数完美转发到函数指针:按值传递呢?
- 为什么我不能将引用作为 std::async 的函数参数传递
- 什么..(省略号)作为函数原型中唯一的函数参数,C++?
- 是否可以就地构造一个固定大小的数组作为函数参数?
- 接受模板作为函数参数
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- Arduino 函数参数