A 3rd party SDK defines several typedefs, e.g.:
typedef unsigned char SDK_BYTE
typedef double SDK_DOUBLE
typedef unsigned char SDK_BOOLEAN
You could do it like this:
SDK_BYTE asByte(SdkVariant & var)
{
SDK_BYTE byte;
bool const ok = var.toByte(byte);
if (!ok) diePainfully();
return byte;
}
SDK_DOUBLE asDouble(SdkVariant & var)
{
SDK_DOUBLE d;
bool const ok = var.toDouble(d);
if (!ok) diePainfully();
return d;
}
SDK_BOOLEAN asBoolean(SdkVariant & var)
{
SDK_BOOLEAN b;
bool const ok = var.toBool(b);
if (!ok) diePainfully();
return b;
}
static const bool byteAndBooleanAreTheSame = std::is_same::value;
template
struct VariantCastImpl
{
template T cast(SdkVariant & var) const;
template <> SDK_DOUBLE cast(SdkVariant & var) const { return asDouble(var); }
template <> SDK_BYTE cast(SdkVariant & var) const { return asByte(var); }
template <> SDK_BOOLEAN cast(SdkVariant & var) const { return asBoolean(var); }
};
template <>
struct VariantCastImpl
{
template T cast(SdkVariant & var) const;
template <> SDK_DOUBLE cast(SdkVariant & var) const { return asDouble(var); }
template <> SDK_BYTE cast(SdkVariant & var) const
{
if (var.type() == SdkVariant::SdkByte)
{
return asByte(var);
}
else if (var.type() == SdkVariant::SdkBoolean)
{
return asBoolean(var);
}
else
{
diePainfully();
return SDK_BYTE(); // dummy return, I assume diePainfully throws something
}
}
};
template
T variant_cast(SdkVariant & var)
{
return VariantCastImpl().cast(var);
};