我一直在使用一组模板来确定给定 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 模板,您可以或多或少地将您的用户定义类型视为对它们应用相同的 boost 规则的原语。因此,我想我要问的问题是这是否可能有用?如果是这样,为了便于使用,您希望模板化哪些类型的常见任务?我正在假设仅拥有促销模板不足以实际采用。
顺便说一下,Boost 在它的数学/工具/促销头文件中有类似的东西,但它实际上更多的是让值准备好传递给标准的 C 数学函数(期望 2 个整数或 2 个 double 数)并绕过所有整数类型。与完全控制对象的转换方式相比,这种简单的事情更可取吗?
TL;DR:除了执行 boost 本身的机制之外,您希望在算术 boost header 中找到哪些类型的帮助器模板?
最佳答案
这绝对有用——我们在数学库中使用了这些东西,我正在使用这些东西在表达式中正确键入中间值。例如,您可能有一个模板化的加法运算符:
template<typename Atype, typename Btype>
type_promote<Atype, Btype>::type operator+(Atype A, Btype B);
通过这种方式,您可以编写一个通用运算符来处理不同的参数类型,它将返回一个适当类型的值以避免出现它的表达式中的精度损失。它也很有用(在 vector 和之类的东西中)在这些运算符中声明内部变量。
至于这些应该怎么做的问题:我刚刚检查了我们定义它们的源代码,我们所拥有的只是您描述的简单 ArithmeticPromotion 声明——三个通用版本来解决复杂的、复杂的-real 和 real-complex 变体,使用特定的真实的真实变量,然后是真实真实变量的列表——总共大约 50 行代码。我们没有任何其他帮助模板,而且(从我们的使用情况来看)看起来我们不会使用任何自然的模板。
(FWIW,如果你不想自己写这个,请从 http://www.codesourcery.com/vsiplplusplus/2.2/download.html 下载我们的源代码,然后拉出
src/vsip/core/promote.hpp
。这甚至在我们的库中是 BSD 许可的部分,尽管它实际上并没有在文件本身中这么说.)关于c++ - C++ 算术 boost header 的使用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2426330/