I would like to put another question about matrix operations...
template <typename T>
struct TMatrix
{
typedef std::vector < std::vector <T> > Type;
};
template <typename T>
class Mat开发者_运维技巧rix
{
private:
typename TMatrix <T>::Type items;
const unsigned int rows_count;
const unsigned int columns_count;
public:
template <typename U>
//Error, see bellow please
Matrix ( const Matrix <U> &M ):
rows_count ( M.getRowsCount() ), columns_count ( M.getColumnsCount() ), items ( M.getItems()){}
unsigned int getRowsCount() const {return rows_count;}
unsigned int getColumnsCount() const {return columns_count;}
typename TMatrix <T>::Type const & getItems () const {return items;}
typename TMatrix <T>::Type & getItems () {return items;}
Compiling the code, the compiler stops here:
Matrix ( const Matrix <U> &M ):
rows_count ( M.getRowsCount() ), columns_count ( M.getColumnsCount() ), items ( M.getItems()){} //Error
and shows the following error:
Error 79 error C2664: 'std::vector<_Ty>::vector(const std::allocator<_Ty> &)' : cannot convert parameter 1 from 'const std::vector<_Ty>' to 'const std::allocator<_Ty> &'
But I do not know, why... Thanks again for your help...
Updated question:
Compiling the code
template <class T>
template <typename U>
Matrix <T> :: Matrix ( const Matrix <U> &M )
: rows_count ( M.getRowsCount() ), columns_count ( M.getColumnsCount() ), items ( M.getItems().begin(), M.getItems().end()){}
with the following result:
Error 132 error C2664: 'std::vector<_Ty>::vector(const std::allocator<_Ty> &)' :
cannot convert parameter 1 from 'const std::vector<_Ty>' to 'const std::allocator<_Ty> &'
c:\program files\microsoft visual studio 10.0\vc\include\xmemory 208
Your templated constructor Matrix<T>::Matrix<U>(const Matrix<U> &M)
is designed to construct a Matrix<T>
given a Matrix<U>
. It does this by invoking the constructor vector<vector<T>>(vector<vector<U>>)
in the initializer list.
The problem is that std::vector
does not provide a mixed-type constructor.
I don't know how to solve this in the initializer list. You might do it in the body of the constructor. Here are updates to your public interface to allow this:
Matrix() : rows_count(), columns_count(), items() {}
template <typename U>
Matrix ( const Matrix <U> M ):
rows_count ( M.getRowsCount() ), columns_count ( M.getColumnsCount() ), items ( ) {
for(int i = 0; i < M.getItems().size(); i++) {
items.push_back(std::vector<T>(M.getItems()[i].begin(),M.getItems()[i].end()));
}
}
You forgot to #include <vector>
at the top and a };
at the end of the file. When I add these to the code, it compiles just fine on my computer.
精彩评论