tags:

views:

54

answers:

4

Here's the code. Is it possible to make last line work?

#include<iostream>
using namespace std;

template <int X, int Y>
class Matrix
{
    int matrix[X][Y];
    int x,y;
    public:
    Matrix() : x(X), y(Y) {}
    void print() { cout << "x: " << x << " y: " << y << endl; }
};

template < int a, int b, int c>
Matrix<a,c> Multiply (Matrix<a,b>, Matrix<b,c>)
{
    Matrix<a,c> tmp;
    return tmp;
}

int main()
{
    Matrix<2,3> One;
    One.print();
    Matrix<3,5> Two;
    (Multiply(One,Two)).print();    // this works perfect
    Matrix Three=Multiply(One,Two); // !! THIS DOESNT WORK
    return 0;
}
+3  A: 
sbi
@sbi, I agree with all your code review notes. Be aware that 1 is controversial. Herb Sutter is known to prefer that style. I see his reasoning. He thinks it only ok for `using namespace std;` all others are prohibited. That said, a global `using` in a header is always a bad idea. Again I agree with 1.
caspin
BTW, C++0x may not be finalized until 2012, so C++11 is just as misleading as C++0x. I prefer C++0x as it is better known and no one expects it to be released in 2009.
caspin
@Caspin: This isn't a header (there's a `main()` function implemented), but still. If Sutter indeed says `using namespace std;` is fine, he is not alone, basically all introductionary C++ books and tutorials use it - which I find very sad. It leads to the kind of subtle bugs as in the question I linked to. [I just ranted about this extensively the other day.](http://stackoverflow.com/questions/2879555/2880136#2880136)
sbi
@Caspin: Every deadline given so far was exceeded. (And I never really bought the hexadecimal argument.) We may need to coin it __Standard C++ 2.0__ then.
sbi
+2  A: 

This wont be possible in C++03 but C++0x offers auto.

auto Three=Multiply(One,Two);
pmr
A: 

Templates are used at compilation time and are used to implement static polymorphism. This means you should know everything about your objects at the moment your code is being compiled.

Hence, here the compiler fails, because this would be too hard for it to know that Three should have (2,5) dimensions (at least at currently common standard).

If this is a question for "just-to-know", then OK, but in real code you should obviously use constructors to initialize matrix (and set it's dimensions).

Kotti
+1  A: 

No, when using a class template, you have to specify all template arguments explicitly.

If your compiler supports it, you can use auto from C++0x instead:

auto Three=Multiply(One,Two);

In g++, you can enable C++0x support using the -std=c++0x flag.

Thomas