Question

Is it possible to make it so that you don't have to overload a function definition 3 times if you want to be able to pass between 1 to 3 parameters into it?

For example instead of:

function(class a) { //this is called if only 1 class is passed
instance 1 = a;
} 
function(class a, class b) {  //this is called if 2 classes are passed
instance1 = a;
instance2 = b;
}
function(class a, class b, class c) { //this is called if 3 classes are passed
instance1 = a;
instance2 = b;
instance3 = c;
}

You could have:

function(class a, <if2class>class b, <if3class>class c) //this is called
                                                        //for all passes
// <ifxclass> is not a real command, I'm using it for demonstration
{
    instance1 = a; //always
    instance2 = b; //if class b is passed
    instance3 = c; //if class c is passed
}

For the function call...

function(first, second) //example of a function call with this code

EDIT: explanation for a real use:

bossbattle(biglion, bigtiger);
bossbattle(biglion);
bossbattle(hades, biglion, biglion);
//where inside bossbattle it sets the classes passed in to temporary classes
//for battle. that's why I need a variable number of parameters

I have already created a battle system for normal enemies and it calls a function to randomly populate 1-3 spots based on a tiered percentage with random normal enemies. I'm trying to use that same battle system but with a different function (i.e. boss battle()) to populate the battle system with a boss fight. The class instances that the temporary enemies use for the battle are in an array named Enemy battlefield monsters[3] and I have a boolean isalive in each instance of the array which I want to be set to true if parameters are called in bossbattle() So for example there will be 3 isalive = true if there are 3 parameters passed into bossbattle() but only 1 set to true if only 1 parameter is passed.

Was it helpful?

Solution

Use default parameters to achieve this. Something like:

void foo(int arg, int arg2 = 0, int arg3 = 0) {
    ...
}

which allows you to call foo and pass either 1, 2 or 3 arguments to it.


Since you've mentioned your actual intentions: i.e. call "bossbattle(hades, biglion, biglion); where inside bossbattle it sets the classes passed in to temporary classes for battle".

In case this bossbattle is constrained with the amount of (let's call it) battle participants (i.e. there will always be 1 to 3 participants), then you can use the aforementioned approach. Otherwise it might be more reasonable to define a class that extracts whatever "hades", "lion" and "tiger" have in common to define the base class, let's say class Creature, and change the interface to take a container of creatures instead:

void bossbattle(const std::vector<Creature>& battleParticipants) {
    ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top