Bak Itzik
Bak Itzik

Reputation: 486

How can I pass a default argument of other type to a parameter?

Lets say I have this prog.cc file:

struct MyStruct
{
  unsigned int X : 2;
  unsigned int Y : 2;
  unsigned int Spare : 28;
};

void MyFunc (int x, MyStruct myStruct = 0);


int main ()
{
    MyStruct myStr;
    myStr.X = 1;
    myStr.Y = 0;
    MyFunc(6);
}

void MyFunc (int x, MyStruct myStruct)
{
    x += 10;
}

When compiled with GCC 4.4.7, I got this error:

prog.cc:7: error: default argument for 'MyStruct myStruct' has type 'int'

Now, I understand the error, but still - how can I resolve this? I know I need somehow to cast from int to MyStruct, but both

MyStruct myStruct = (MyStruct)0

and

MyStruct myStruct = static_cast<MyStruct>0

has failed with:

prog.cc:7: error: no matching function for call to 'MyStruct::MyStruct(int)'

prog.cc:1: note: candidates are: MyStruct::MyStruct()

prog.cc:1: note: MyStruct::MyStruct(const MyStruct&)

How can I simply initialize my user-defined struct, passed as default argument on function parameter?

(Here is the sample code: http://melpon.org/wandbox/permlink/izWCnBXl9PGnmm0l)

Upvotes: 0

Views: 61

Answers (2)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385365

You can default-initialise PODs, so:

void MyFunc (int x, MyStruct myStruct = MyStruct());

I guess you're trying to use 0 because, as well as being an integer, that's a null pointer constant. But you're not using pointers here. The use of 0 is the wrong approach.

Upvotes: 7

YSC
YSC

Reputation: 40150

Just add a conversion constructor to your MyStruct:

struct MyStruct
{
  unsigned int X : 2;
  unsigned int Y : 2;
  unsigned int Spare : 28;
  MyStruct(int n) : X(n&3), Y(n&12), Spare(0) {}
};

It's implementation depends on your semantics, but you get the technical point. Enclosing your struct in an union could be a good solution too if you want to make it convertible from/to an int.

Upvotes: 1

Related Questions