[英]template different return types
在下面的代码中,我必须将boolean_cast强制转换为TDestination,以避免出现编译器警告(从“ VARIANT_BOOL”截断为“ bool”)。 这是编译器问题还是C ++问题?
template<typename TDestination, typename TSource>
TDestination boolean_cast(TSource source)
{
TDestination destination;
static_assert(std::is_same<TDestination, bool>::value || std::is_same<TDestination, VARIANT_BOOL>::value, "destination must be bool or VARIANT_BOOL");
//convert to bool
if (std::is_same<TDestination, bool>::value)
{
if (source)
destination = true;
else
destination = false;
}
//convert to VARIANT_BOOL
else
{
if (source)
destination = (TDestination)VARIANT_TRUE;
else
destination = (TDestination)VARIANT_FALSE;
}
return destination;
}
就像@nm在评论中说的那样,当目标类型为bool
且目标类型为VARIANT_BOOL
时,编译器不会停止编译if
的false分支,因此两个分支都必须是有效代码。
您可以通过分派到专门针对目标类型的帮助程序模板来避免该问题
template<typename TDestination, typename TSource>
struct boolean_cast_impl; // undefined
template<typename TSource>
struct boolean_cast_impl<bool, TSource>
{
static bool cast(TSource source)
{
return source ? true : false;
}
};
template<typename TSource>
struct boolean_cast_impl<VARIANT_BOOL, TSource>
{
static VARIANT_BOOL cast(TSource source)
{
return source ? VARIANT_TRUE : VARIANT_FALSE;
}
};
template<typename TDestination, typename TSource>
TDestination boolean_cast(TSource source)
{
static_assert(std::is_same<TDestination, bool>::value || std::is_same<TDestination, VARIANT_BOOL>::value, "destination must be bool or VARIANT_BOOL");
return boolean_cast_impl<TDestination, TSource>::cast(source);
}
甚至只是在专业化中定义正确类型的常量:
template<typename TDestination, typename TSource>
struct boolean_cast_values; // undefined
template<typename TSource>
struct boolean_cast_values<bool, TSource>
{
static const bool true_ = true;
static const bool false_ = false;
};
template<typename TSource>
struct boolean_cast_values<VARIANT_BOOL, TSource>
{
static const VARIANT_BOOL true_ = VARIANT_TRUE;
static const VARIANT_BOOL false_ = VARIANT_FALSE;
};
template<typename TDestination, typename TSource>
TDestination boolean_cast(TSource source)
{
static_assert(std::is_same<TDestination, bool>::value || std::is_same<TDestination, VARIANT_BOOL>::value, "destination must be bool or VARIANT_BOOL");
typedef boolean_cast_values<TDestination, TSource> values;
return source ? values::true_ : values::false_;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.