I have some templated C++-03 code that includes a snippet that I'd like to write something like this:
template <typeName optType>
std::string
example(optType &origVal)
{
return bool(origVal) ? "enabled" : "disabled";
}
However, there is no optType::operator bool()
defined for struct linger
and I cannot add one as that struct
is not mine. Therefore, for now, I have written it as this instead:
template <typename optType>
bool
castBool(const optType &value)
{
return bool(value);
}
template <>
bool
castBool<struct linger>(const struct linger &value)
{
return bool(value.l_onoff);
}
template <typeName optType>
std::string
example(optType &origVal)
{
return castBool(origVal) ? "enabled" : "disabled";
}
But, I'm wondering if there is a more succinct way to do this? For example, I can define a static operator==()
outside of a class, such as like this:
bool
operator==(const struct linger &lhs, const struct linger &rhs)
{
return lhs.l_onoff == rhs.l_onoff && lhs.l_linger == rhs.l_linger;
}
So perhaps there is some syntax to tell the compiler how to promote a struct such as the struct linger
here to a bool?