[英]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:
我可能会执行以下操作之一:
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.