开发者

Returning multiple values and default parameters in C++

I'm trying to make a function that takes in either 1 or 3 parameters, and returns either 1 or 3 values (based on parameters passed).

If 1 parameter is passed then the function uses default values for the other 2 arguments. If 3 parameters are passed then it uses those values.

bool foo( 开发者_运维知识库bool x, int &y = 0, int &z = 0) {

x = true; y = y + 1; z = z + 2;

return x;

}

Is this possible in C++ or am I confused with Java functions.


You can do it with two functions:

bool foo( bool x, int &y, int &z) {
    x = true; // this isn't really what it does, is it?
    y = y + 1; z = z + 2;
    return x;
}

bool foo(bool x)
{
    int a = 0, b = 0;
    return foo(x,a,b);
}


Any function always returns only 1 value. Returning 2 or more values is not possible directly.

Indirectly, it happens when you pass parameters by reference. Since the two parameters &y and &z are passed by references, hence changes to them can be reflected back directly.


You can do this by passing by reference..

by doing so you are making a method that points to a memory location. When that memory location is changed, then your value is changed.

Link http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr233.htm


You cannot do that this way. You can, however, overload that function with different number of parameters, and return, maybe, a std::vector or std::list with the results.

EDIT:

Being more sophisticated, you can use tuples for that:

typedef boost::tuple<bool,int,int> my_data_t;
my_data_t my_tuple(true, 1, 0);

then, you define your function like this:

bool foo( my_data_t & t)
{
    t.get<0>() = true;
    int& y = t.get<1>();
    y = y+1;
    int& z = t.get<2>();
    z = z+2;
    return t.get<0>();
}

and call it this way:

bool result = foo ( my_tuple );

then, out of the function, you'll see my_tuple.get<1>() (the corresponding to y) as 2 (1+1).


I am not sure what you are trying to do, but you can kind of return multiple values of different type using boost::tuple.

boost::tuple<bool, int, int> foo( bool x, int y = 0, int z = 0) {

    x = true; y = y + 1; z = z + 2;

    return boost::make_tuple(x, y, z);

}

int main() {
    boost::tuple<bool, int, int> result = foo(x, 1, 2);

    std::cout << boost::get<0>(result) << boost::get<1>(result) << boost::get<2>(result);
}

You could also use boost::optional, if you only want to return x, if only 1 parameter is passed.

Btw. tuple is available in C++11 too.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜