Introduction
Someone asked me how to implement a default parameter value for a struct
. He wanted to make it possible to make the following calls:
MyStruct st = {200,50);
foo();
foo(st);
He had tried the following:
struct MyStruct
{
int a;
int b;
};
void foo(MyStruct st={100,100})
{
cout << st.a << " " << st.b << endl;
}
The compiler (VC 6) however didn't compile this.
Solutions
You can use a constructor in your struct
. It's not really nice but it will work.
struct MyStruct
{
MyStruct(int x, int y)
{
a = x;
b = y;
}
int a;
int b;
};
void foo(MyStruct st=MyStruct(100,100))
{
cout << st.a << " " << st.b << endl;
}
The second solution, I like a little more:
struct MyStruct
{
int a;
int b;
};
static const MyStruct stDefValue = { 100, 100 };
void foo(MyStruct st=stDefValue)
{
cout << st.a << " " << st.b << endl;
}
Conclusion
It's not a big deal and you may find it not nicely programmed in an OO way, but it is handy to know when you want to do something like this.