Reputation: 1
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?
Upvotes: 0
Views: 1158
Reputation: 254631
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
}
Upvotes: 9
Reputation: 477358
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.
Upvotes: 4
Reputation: 10562
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).
Upvotes: 2