Is it possible to have template class arguments specified by the compiler, when passed in as a parameter?
Is it possible to have template class arguments specified by the compiler, when passed in as a parameter?
Consider the following:
I'm writing a Matrix class in C++, which looks like this:
template<unsigned rows, unsigned cols>
class matrix
...
;
Now, writing the multiply method, I've come to a problem: The left - "this" - matrix must have the same number of columns which the right - "o" - matrix has rows, but how many columns o has, is irrelevant, see below:
const matrix<rows, rows> mul(const matrix<cols, /*This can be anything*/>&& o)
...
My question is, is there any way to tell the compiler, that it should take the template argument of o for its unknown second argument?
So then I can take the template argument of mul and put it inside the column argument of o?
– AProgrammer
Aug 23 at 14:55
Note that constant rvalue references (like the argument to your
mul
function) is almost always useless. Perhaps you really should use a constant lvalue reference, as in const matrix<cols, ...>&
(note the single &
)?– Some programmer dude
Aug 23 at 14:56
mul
const matrix<cols, ...>&
&
@Someprogrammerdude Well, yes I guess, I haven't really figured out, when to use rvalue references instead of lvalue references to achieve the best result
– AProgrammer
Aug 23 at 14:58
1 Answer
1
is there any way to tell the compiler, that it should take the
template argument of o for its unknown second argument?
Yes indeed, this is exactly what templates does for you : )
Just write mul()
as a member function template instead of a member function.
mul()
template<unsigned rows, unsigned cols>
class matrix
...
template <unsigned rhsRows>
matrix<rows, rhsRows> mul(const matrix<cols, rhsRows>& o) const
...
;
Note: const
was moved to made the member function template const instead of being const for the return value, as being there it can disable move semantics, and as the semantics of multiplying matrices shouldn't change any of the operands if returning a result.
const
Thanks, sometimes the solutions are simpler, than one thinks :)
– AProgrammer
Aug 23 at 14:56
The return type was originally
matrix<rows, rows>
(rows
twice). Additionally, there is no reason to make the return value const
, it can disable move semantics.– François Andrieux
Aug 23 at 15:01
matrix<rows, rows>
rows
const
@FrançoisAndrieux Good point, I'm really new to move semantics and stuff, so this helps me greatly. Going to rewrite my vector and point classes now as well ;)
– AProgrammer
Aug 23 at 15:03
@FrançoisAndrieux You too friend
– SkepticalEmpiricist
Aug 23 at 15:03
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Just make that function a template. Class templates can have member function templates.
– François Andrieux
Aug 23 at 14:54