0

In C++, I want to have a function that takes an optional argument of type vector. If the argument is not provided, I want the variable to have size 0. I currently have

void v_connect::import(vector<int> vid_,vector<double> vpos_,vector<int> vbd_,vector<int>    bd_ss_=std::vector<int>() )

But this doesn't work. Basically, if the user provides the optional argument bd_ss_ I want to do a check bd_ss_.size()!=0 and then do some extra stuff. If the user does not provide the argument, I want bd_ss.size()==0. Is this possible?

Gordon Bailey
  • 3,881
  • 20
  • 28

3 Answers3

9

There is no way to tell whether or not an optional argument is user-provided. However, you could use an overload:

void v_connect::import(
    std::vector<int> vid_,
    std::vector<double> vpos_,
    std::vector<int> vbd_,
    std::vector<int> bd_ss_) 
{
    check(!bd_ss_.empty());
    do_extra_stuff();
    do_import(vid_, cpos_, vbd_, bd_ss_);
}

void v_connect::import(
    std::vector<int> vid_,
    std::vector<double> vpos_,
    std::vector<int> vbd_) 
{
    do_import(vid_, cpos_, vbd_, std::vector<int>());
}

// private:
void v_connect::do_import(
    std::vector<int> vid_,
    std::vector<double> vpos_,
    std::vector<int> vbd_,
    std::vector<int> bd_ss_)
{
    // common import code goes here
}
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
4

You could make the user pass a pointer instead:

void foo(std::vector<int> * ov = NULL)
{
    std::vector<int> dummy;
    std::vector<int> & bd_ss_ = ov ? *ov : dummy;

    if (ov) assert(!bd_ss_.empty());

    // ...
}

Alternatively, use Boost.optional, which is a clever C++-style wrapper around this idea and allows you to have the same behaviour with a seamless interface.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
2

Optional parameters go in the header, not the cpp.

As an aside you're mixing vector and std::vector, use one or the other (prefer to stick to std::vector).

DanDan
  • 10,462
  • 8
  • 53
  • 69
  • 2
    Not 100% true, each argument can be defaulted in the header or the implementation (more precisely: declaration or definition) as long as when an argument is defaulted, all later arguments in the signature are defaulted (or have been previously defaulted). +1 anyway, as this is most probably the cause of the issue. – David Rodríguez - dribeas Aug 06 '12 at 16:27