Say I have a type Thing
which can be converted to a primitive type such as int
, should I prefer defining an explicit user-defined conversion operator such as:
struct Thing
{
int member = 42;
explicit operator int() const { return member; }
};
int main()
{
Thing thing;
return static_cast<int>(thing);
}
Or should I just go with a plain named function:
struct Thing
{
int member = 42;
int asInt() const { return member; }
};
int main()
{
Thing thing;
return thing.asInt();
}
It appears to me like the statement of intent is similar, and I think the syntactical merits of both could be argued, but perhaps there are more subtle reasons to use one or the other. Does anyone have experience of the pros and cons of each?
Aucun commentaire:
Enregistrer un commentaire