开发者

C++: How do I pass N arguments to a function where N can be any number > 0? (The function already exists as part of an external library)

开发者 https://www.devze.com 2023-02-22 18:42 出处:网络
This is the way I currently call the function: struct fann *ann = fann_create_standard( num_layers, num_in,

This is the way I currently call the function:

struct fann *ann = fann_create_standard(
                          num_layers, 
                          num_in,
                          optional_num_1, 
                 开发者_开发问答         optional_num_2, 
                          num_out);

the function above can have at least 3 arguments... the required arguments are num_layers, num_input, and num_output)

the optional arguments are the hidden layers of the neural network (what they are call isn't important.... but basically... it could look like this:

fann_create_standard(#layers, 
                       #input,
                       #hidden1,
                       #hidden2,
                       #hidden3,
                       #hidden4,
                       ...,
                       #hiddenN,
                       #output);

what I want to be able to do, is pass in command line arguments to change how many layers, and what the values of each of the hidden layers are (the middle arguments in this function call), so that I don't have to re-compile the program every time I want to re-configure the network.


can't you use fann_create_standard_array to do what you want? Arrays can be dynamically created, whereas argument lists should be specified during compilation.


Add the stdarg.h library file into your program.

In your case your function definition will be:

fann_create_standard(num_layers , num_in , num_out , int count,  ... );

Then you can access your optional parameters using the va_start, va_args, va_end macros and the va_list type to retrieve your optional parameters. The new "count" parameter holds the amount of parameters you pass to the method, so:

fann_create_standard(num_layers , num_in , num_out , int count,  ... ){
  int i;
  YOUR_TYPE val;
  va_list vl;
  va_start(vl,count);
  for (i=0;i<count;i++)
  {
    val = va_arg(vl,YOUR_TYPE);
    //val is your optional parameter, do whatever you'd like with it
  }
  va_end(vl);
}


What you're looking for is a variadic function

0

精彩评论

暂无评论...
验证码 换一张
取 消