Flo*_*ate 9 c++ templates inline matrix
我正在创建一个简单的Matrix类.我试图添加一个未命名的模板参数,以确保它与整数类型一起使用
#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_;
};
Run Code Online (Sandbox Code Playgroud)
我想在类定义之外定义构造函数
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)
{};
Run Code Online (Sandbox Code Playgroud)
g ++返回以下错误
Matrix.hh:25:50: error: invalid use of incomplete type ‘class Matrix<T>’
inline Matrix<T>::Matrix(size_t nrow, size_t ncol)
Run Code Online (Sandbox Code Playgroud)
你知道如何解决这个问题吗?
提前致谢.
模板参数名称是每个模板声明的"本地".没有什么可以阻止您分配名称.如果您以后需要引用该参数(例如将其用作类的template-id中的参数),您确实必须这样做.
所以,虽然你在类定义中有这个:
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_;
};
Run Code Online (Sandbox Code Playgroud)
你可以在课外定义它,例如:
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)
{};
Run Code Online (Sandbox Code Playgroud)
只是不要忘记,在常见情况下,模板只能在头文件中定义.