C ++如何在没有前面参数的情况下使用省略号 [英] C++ how to use ellipsis without a preceding argument

查看:22
本文介绍了C ++如何在没有前面参数的情况下使用省略号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨我有一个带有成员函数的类,它采用可变数量的参数.该类知道实例化后需要多少个参数.例如

Hi I have a class with a member function that takes a variable number of arguments. The class knows how many arguments to expect once it is instantiated. e.g

class myClass
{
 myClass(int num_args){na=num_args;};
 private:
 int na;
 public:
 void do_something(int num_args, ...);
}

void myClass::do_something(int num_args, ...)
{
 va_list vl;
 va_start(vl, num_args);
 for(int i=0; i < num_args; i++)
  do_anotherthing(va_arg(vl, type));
 va_end
}

所以我最终调用如下:

myClass A(5);
myClass B(4);

A.do_something(5, a, b, c, d, e);
B.do_something(4, a, b, c, d);

对我来说,必须不断指定我传递的参数数量似乎很不整洁.解决这个问题的最佳方法是什么?我考虑过重载一堆函数,每个函数都有 n 个参数,一个宏来为我放入 num_args.但理想情况下,我希望能够将 do_something 定义为

It seems untidy to me to have to keep specifying the number of arguments i'm passing. What's the best way to get around this? I've considered overloading a bunch of functions, each with n arguments, a macro to put the num_args in for me. But ideally I'd like to be able to define do_something as

void do_something(...);

并以某种方式让 stdargs 的东西与类的 num_args 而不是传入的值一起工作.

and somehow get the stdargs stuff to work with the class's num_args rather than a value passed in.

非常感谢您的想法.

推荐答案

请不要那样做.可变数量的参数在 C++ 中非常罕见

Please don't do that. Variable number of parameters is very uncommon in C++

实现您想要的最佳方法是创建一个 int 列表并将该列表作为参数传递

The best way to achieve what you want is to create a list of int and pass that list as a parameter

可以在函数内部查看列表的大小

you can check the size of the list inside the function

这篇关于C ++如何在没有前面参数的情况下使用省略号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆