简体   繁体   中英

Compile time template values deduction

I have this template matrix struct (I provided a constructor which takes std::initializer_list):

template<int rows, int cols, typename scalar = float>
struct matrix;

with a product operator defined outside the matrix struct, like this:

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

and then declared as a friend inside the struct. So if I instantiate two matrices:

matrix<2, 3> A = { 1, 2, 3, 4, 5, 6 };
matrix<3, 2> B = { 7, 8, 9, 10, 11, 12 };

and I want to create a matrix C = A * B, I have to write:

matrix<2, 2> C = A * B;

And that's fine, but is there a way to omit the <2, 2> template? I believe that it can be deducted at compile time (because auto works fine):

auto C = A * B; // no errors

I'd like to write just matrix instead of auto , is it possible?

No, you cannot (if you don't have some non-template base matrix). matrix is not a type, it's template and you should specify template parameters. auto is simplest thing, that you can do. Or, instead of auto you can use decltype

decltype(A * B) C = A * B;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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