我正在创建一个简单的 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_;
};
我想在类定义之外定义构造函数
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++ 返回以下错误
Matrix.hh:25:50: error: invalid use of incomplete type ‘class Matrix<T>’
inline Matrix<T>::Matrix(size_t nrow, size_t ncol)
你知道如何解决这个问题吗?
提前致谢。
最佳答案
模板参数名称对于每个模板声明都是“局部的”。没有什么能阻止您分配名称。如果您稍后需要引用该参数(例如将其用作类的模板 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_;
};
您可以在类之外定义它,例如像这样:
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)
{};
只是不要忘记,在一般情况下,templates can only be defined in header files .
关于C++:如何在类成员中使用未命名的模板参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35651531/