I'm trying to figure out how I can "pass default struct values" to a function without initializing the struct, this is what I have now:
struct Color3i
{
Color3i(): r(255), g(255), b(255) { }
int r, g, b;
};
void CCore::Color(Color3i color)
{
double red, green, blue;
red = color.r / 255.0f;
green = color.g / 255.0f;
blue = color.b / 255.0f;
glColor3f(red,green,blue);
}
Color3i defaultColor;
Core.Color(defaultColor);
What I'm trying to do would look like this but this clearly doesn't work:
Core.Color(Color3i defaultColor);
How would I pass the struct to the function without initializing it with Color3i defaultColor; is this possible?
Sorry if this has been asked before but I tried searching the interwebs but I couldn't find anything (maybe I'm using the wrong keywords to search)
You should just be able to do this:
Core.Color(Color3i());
That is, call the default constructor to initialize a new instance, and pass it.
There are a few ways to pass an information that you want the color to be default. The simplest one is given in the comments already:
Core.Color(Color3i())
If you want the code to be shorter, you can set the default value in the function parameter you invoke:
void CCore::Color(Color3i color = Color3i()) { ... }
....
Core.Color(); //no argument = default
If you want to be more descriptive instead, you can create a static function acting as a constructor in the Color
:
struct Color3i {
Color3i(): r(255), g(255), b(255) { }
int r, g, b;
static Colo3i defaultColor() { return Color3i(); }
};
...
Core.Color(Color3i::defaultColor());
Finally, if you want to control the context where the default color can be used, you can create a new dummy enum type and overload the function(s) to accept the default version explicitly:
enum DefaultColorEnum {
DefaultColor
};
void CCore::Color(Color3i color) {
... //normal code
}
void CCore::Color(DefaultColorEnum) { //ignore the parameter value, the type is what matters
Color(Color3i()); //invoke the generic version with default value
}
...
Core.Color(DefaultColor);
It all depends on what you actually wants to achieve...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.