简体   繁体   English

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

[英]Templated implicit type conversion operator

I have implemented 我已经实施

template<int M, int N, typename T=double>
class matrix{
    // ...
}

and would like the ability to use matrix<1,1,T> where a T is expected. 并希望在期望T情况下使用matrix<1,1,T>的能力。

How should I accomplish this? 我应该如何做到这一点? Would the following work? 以下工作有效吗?

template<typename T>
operator T(matrix<1, 1, T> mat) {
    return mat(0,0);
}

(The reason for even expecting to encounter matrix<1,1,T> is that some matrix expressions have that type. For example, multiplying a matrix<1,3> by a matrix<3,1> evaluates to a matrix<1,1> .) (甚至期望遇到matrix<1,1,T>是某些矩阵表达式具有该类型。例如,将matrix<1,3>乘以matrix<3,1>得出matrix<1,1> 。)

The code you've listed will not compile, since you're essentially trying to implement a T constructor outside the definition of T ; 您所列出的将不能编译,因为你基本上是试图实现的代码T的定义之外构造T ; or if it's a fundamental type, or an array, it makes even less sense. 或者,如果它是基本类型或数组,那么意义就更小了。

What you can do instead is implement a casting operator within your matrix class - by either adding it to the general template or specializing matrix for M=1 and N=1. 您可以做的是在矩阵类中实现强制转换运算符-通过将其添加到常规模板或对M = 1和N = 1进行特殊化的matrix

The first option would look like this: 第一个选项如下所示:

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

and the second: 第二个:

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

but frankly, I don't think I'd recommend any of these options. 但坦率地说,我不建议您使用任何这些选项。 I'd probably do one of the following: 我可能会执行以下操作之一:

  • Alter function which takes a T so that it can "naturally" take 1x1 matrices (eg by templating) Alter函数采用T,以便“自然”采用1x1矩阵(例如通过模板化)
  • Alter function which takes a T so that it can "naturally" take any matrix. Alter函数采用T,以便它可以“自然”采用任何矩阵。 A lot of scalar work has interesting generalization to matrices. 许多标量工作对矩阵都有有趣的概括。
  • Be explicit about the conversion, perhaps writing a template <typename T> T as_scalar(const matrix<1,1,T> m) function. 要明确转换,也许写一个template <typename T> T as_scalar(const matrix<1,1,T> m)函数。

Put this in the class definition: 将其放在类定义中:

template<int Md=M, int Nd=N, typename = std::enable_if_t<Md==1 && Nd==1>>
operator T() const {
    return (*this)(0,0);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM