模板化隐式类型转换运算符

Templated implicit type conversion operator

本文关键字:类型转换 运算符      更新时间:2023-10-16

我已经实现了

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);
}