C ++: How to use name parameters without a name in classes?

I am creating a simple Matrix class. I am trying to add a parameter without a template name to make sure that it is used with built-in types

#include <string> #include <vector> #include <boost/utility/enable_if.hpp> #include <boost/type_traits/is_scalar.hpp> template <typename T, typename = typename boost::enable_if<boost::is_scalar<T> >::type> class Matrix { public: Matrix(const size_t nrow, const size_t ncol); private: const size_t nrow_; const size_t ncol_; std::vector<std::string> rownames_; std::vector<std::string> colnames_; std::vector<T> data_; }; 

I would like to define a constructor outside the class definition

 template <typename T,typename> inline Matrix<T>::Matrix(size_t nrow, size_t ncol) : nrow_(nrow), ncol_(ncol), rownames_(nrow_), colnames_(ncol_), data_(nrow_*ncol) {}; 

g ++ returns the following error

 Matrix.hh:25:50: error: invalid use of incomplete type 'class Matrix<T>' inline Matrix<T>::Matrix(size_t nrow, size_t ncol) 

Do you know how to solve this problem?

Thanks in advance.

+7
c ++ matrix templates inline
source share
1 answer

Template parameter names are "local" to each template declaration. Nothing prevents you from assigning a name. What should you really do if you need to refer to this parameter later (for example, use it as an argument in the class template identifier).

So, if you have this in your class definition:

 template <typename T, typename = typename boost::enable_if<boost::is_scalar<T> >::type> class Matrix { public: Matrix(const size_t nrow, const size_t ncol); private: const size_t nrow_; const size_t ncol_; std::vector<std::string> rownames_; std::vector<std::string> colnames_; std::vector<T> data_; }; 

You can define it outside the class, for example. eg:

 template <typename AnotherName,typename INeedTheName> inline Matrix<AnotherName, INeedTheName>::Matrix(size_t nrow, size_t ncol) : nrow_(nrow), ncol_(ncol), rownames_(nrow_), colnames_(ncol_), data_(nrow_*ncol) {}; 

Remember that under normal circumstances, templates can only be defined in header files .

+5
source share

All Articles