【发布时间】:2017-06-07 20:31:06
【问题描述】:
我正在尝试为 Vector 类实现基本算术运算,并希望支持混合基础类型,同时防止发生缩小。
template <typename T1,typename T2>
Vector<T1> operator+( Vector<T1> lhs, const Vector<T2>& rhs, std::enable_if< ! is_narrowing_conversion<T2,T1>::value >::type* = nullptr )
{ return lhs += rhs; }
我想实现 is_narrowing_conversion 以便仅在类型不缩小时才允许转换。以下是一些示例:
Vector<double> a = Vector<double>() + Vector<float>(); //OK
Vector<float> a = Vector<float> + Vector<double>; //Fails to find the operator+ function
最后,我想编写第二个模板 operator+ 函数,该函数将通过返回一个 Vector 来处理相反的情况。
我发现这篇文章with an incomplete example。但这还不够,因为他指出它不允许 uint8_t 到 uint64_t 转换。
我还发现了Daniel Krügler's paper on fixing is_constructible。特别是在这篇论文中,他提到了使用列表初始化,它已经具有窄化语义,但我不确定如何将他提到的内容转换为可用于 SFINAE 模板推导的适当特征。
【问题讨论】:
-
我想我应该注意,我已经更新了您链接到上面的帖子作为“不完整示例”,其版本现在应该适用于 uint8_t --> uint64_t 等
标签: c++ c++11 sfinae narrowing