【发布时间】:2015-11-26 17:35:27
【问题描述】:
我有这个模板矩阵结构(我提供了一个构造函数,它采用 std::initializer_list):
template<int rows, int cols, typename scalar = float>
struct matrix;
在矩阵结构外定义乘积运算符,如下所示:
template<int n, int m, int p, typename scalar>
matrix<n, m, scalar> operator*(const matrix<m, p, scalar>& left, const matrix<p, n, scalar>& left);
然后在结构中声明为友元。所以如果我实例化两个矩阵:
matrix<2, 3> A = { 1, 2, 3, 4, 5, 6 };
matrix<3, 2> B = { 7, 8, 9, 10, 11, 12 };
我想创建一个矩阵C = A * B,我必须写:
matrix<2, 2> C = A * B;
这很好,但是有没有办法省略 模板?我相信可以在编译时扣除(因为auto可以正常工作):
auto C = A * B; // no errors
我只想写matrix 而不是auto,可以吗?
【问题讨论】:
-
我认为除非你使用虚拟基础,否则这是不可能的,因为返回类型必须有模板参数。
-
你为什么不试试呢?如果你这样做了,你尝试的时候发生了什么?
-
@cqdjyy01234 即使使用虚拟基类也是不可能的,因为它需要是指针或引用。
-
@CoffeeandCode 也许他会从乘法中返回一个智能指针,并使用 typedef。
-
@cqdjyy01234 那么他的代码就会过于复杂,几乎肯定会造成动态分配的瓶颈。
标签: c++ templates matrix compile-time