模板化隐式类型转换运算符
Templated implicit type conversion operator
我已经实现了
template<int M, int N, typename T=double>
class matrix{
// ...
}
并希望能够在预期T
的地方使用matrix<1,1,T>
。
我应该如何完成此操作?以下方法行得通吗?
template<typename T>
operator T(matrix<1, 1, T> mat) {
return mat(0,0);
}
(甚至期望遇到matrix<1,1,T>
的原因是某些矩阵表达式具有该类型。例如,将matrix<1,3>
乘以matrix<3,1>
的计算结果为matrix<1,1>
.(
你列出的代码不会编译,因为你实际上是在尝试实现T
定义之外的T
构造函数;或者如果它是一个基本类型,或者一个数组,它就更没有意义了。
相反,您可以做的是在矩阵类中实现一个转换运算符 - 通过将其添加到通用模板或专门用于 M=1 和 N=1 的matrix
。
第一个选项如下所示:
template<int M, int N, typename T=double>
class matrix{
// ...
operator T() const {
static_assert(M == 1 and N==1,
"Attempting to treat a matrix with multiple cells as a scalar");
// code to return the single matrix element
}
}
第二个:
template<int M, int N, typename T=double>
class matrix{
// ...
}
template<typename T=double>
class matrix<1, 1, T>{
// ... some code duplication here with the main template; or maybe
// actually have different implementation banking on the fact that
// it's really just a scalar.
operator T() const {
// code to return the single matrix element
}
}
但坦率地说,我认为我不会推荐任何这些选项。我可能会执行以下操作之一:
- Alter 函数,它需要一个 T,以便它可以"自然地"接受 1x1 矩阵(例如通过模板(
- Alter 函数,它采用 T,以便它可以"自然地"接受任何矩阵。许多标量工作对矩阵都有有趣的推广。
- 明确转换,也许编写一个
template <typename T> T as_scalar(const matrix<1,1,T> m)
函数。
把它放在类定义中:
template<int Md=M, int Nd=N, typename = std::enable_if_t<Md==1 && Nd==1>>
operator T() const {
return (*this)(0,0);
}
相关文章:
- 有没有一种方法可以通过"typedef"为重新定义的基本类型定义特征和强制转换运算符
- 将内置类型变量传递给只有一个类类型参数的"+"运算符函数时自动类型转换的构造函数
- 自定义类型转换运算符在转发引用上调用时不起作用(当对象按值传递时有效)
- 模板化隐式类型转换运算符
- 具有重载类型转换运算符的函数对象崩溃
- 仅为某些模板专用化定义转换运算符:预期类型/预期类型说明符
- 类型转换运算符重载与 as 非成员函数
- 从类模板中排除转换运算符...<类型名 T>基于 T 上的特征
- 初始化中的模板转换运算符类型推导规则是什么?
- C++类型转换运算符
- C++:重载运算符.奇怪的类型转换运算符
- 忽略C++重载类型转换运算符
- 在 Visual Studio 10 中使用类型转换运算符重载时出现 C2440 错误
- 使用了构造函数而不是或类型转换运算符
- 模板类中的类型转换运算符 - 无论显式如何都调用
- 与类型转换运算符一起使用时条件运算符"?:"的编译器错误
- C++类型转换运算符代码,在 Visual Studio 2012 中无法编译,但在 Visual Studio 2005 中工作正常
- 为什么类型转换运算符不适用于继承的类?
- 重载类型转换运算符的语法
- 在 C++ 中定义类型转换运算符模板的正确方法是什么?