【发布时间】:2011-01-26 10:44:51
【问题描述】:
我一直在使用一组模板来确定在 C++ 中给定两种基本类型的正确促销类型。这个想法是,如果您定义了一个自定义数字模板,您可以使用它们来确定返回类型,例如,基于传递给模板的类的 operator+ 函数。例如:
// Custom numeric class
template <class T>
struct Complex {
Complex(T real, T imag) : r(real), i(imag) {}
T r, i;
// Other implementation stuff
};
// Generic arithmetic promotion template
template <class T, class U>
struct ArithmeticPromotion {
typedef typename X type; // I realize this is incorrect, but the point is it would
// figure out what X would be via trait testing, etc
};
// Specialization of arithmetic promotion template
template <>
class ArithmeticPromotion<long long, unsigned long> {
typedef typename unsigned long long type;
}
// Arithmetic promotion template actually being used
template <class T, class U>
Complex<typename ArithmeticPromotion<T, U>::type>
operator+ (Complex<T>& lhs, Complex<U>& rhs) {
return Complex<typename ArithmeticPromotion<T, U>::type>(lhs.r + rhs.r, lhs.i + rhs.i);
}
如果您使用这些促销模板,您可以或多或少地将您的用户定义类型视为原语,并应用相同的促销规则。所以,我想我的问题是这会有用吗?如果是这样,您希望模板化哪些常见任务以便于使用?我的工作是假设仅拥有促销模板不足以实际采用。
顺便说一下,Boost 在它的 math/tools/promotion 标头中有类似的东西,但它实际上更多是为了让值准备好传递给标准 C 数学函数(期望 2 个整数或 2 个双精度数)并绕过所有整数类型。比完全控制对象的转换方式更简单吗?
TL;DR:除了执行提升本身的机制之外,您希望在算术提升标头中找到哪些类型的帮助模板?
【问题讨论】:
-
我想在最后你将把提升良好的结果分配给一些变量(不同类型的),所以我看不出它有多少实际用途。也许在 C++0x 中使用 auto,但我也认为 decltype 可以更轻松地完成大部分工作。
-
事实证明,这将在 C++0x 中作为 CommonType 结构实现,它利用 decltype 来找出正确的类型。如果有人想要完全统一的行为与标准关于提升/转换的规则有关,他们只需要编写模板的可交换变体。