是否可以在没有过载的情况下为每个函数提供可变数量的参数?

Sco*_*ott 0 c++ parameters function optional-parameters c++11

如果你想能够将1到3个参数传递给它,是否有可能使它不必重载函数定义3次?

例如,而不是:

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;
}
Run Code Online (Sandbox Code Playgroud)

你可以有:

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
}
Run Code Online (Sandbox Code Playgroud)

对于函数调用...

function(first, second) //example of a function call with this code
Run Code Online (Sandbox Code Playgroud)

编辑:真实用途的解释:

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
Run Code Online (Sandbox Code Playgroud)

我已经为普通敌人创建了一个战斗系统,并且它调用一个函数来根据随机正常敌人的分层百分比随机填充1-3个点.我正在尝试使用相同的战斗系统,但具有不同的功能(即boss battle())用boss战来填充战斗系统.临时敌人用于战斗的类实例位于一个名为的数组中,Enemy battlefield monsters[3]并且我isalive在数组的每个实例中都有一个布尔值,如果在bossbattle() So 中调用参数,我希望将其设置为true ,例如,isalive = true如果有,则会有3个bossbattle()如果只传递了1个参数,则传入3个参数,但只有1个设置为true.

Lih*_*ihO 7

使用默认参数来实现此目的.就像是:

void foo(int arg, int arg2 = 0, int arg3 = 0) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

它允许您调用foo并传递1,2或3个参数.


既然你已经提到过你的实际意图:即调用" bossbattle(hades, biglion, biglion);在里面bossbattle设置传递给临时类进行战斗的类".

如果bossbattle受到(让我们称之为)战斗参与者的数量限制(即总会有1到3名参与者),那么您可以使用上述方法.否则,定义一个提取任何"hades","lion"和"tiger"共同定义基类的类可能更合理,比方说class Creature,并改变接口以取代生物容器:

void bossbattle(const std::vector<Creature>& battleParticipants) {
    ...
}
Run Code Online (Sandbox Code Playgroud)