C++:如何在类成员中使用未命名的模板参数?

标签 c++ templates matrix inline

我正在创建一个简单的 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/

相关文章:

c++ - 为什么可以访问作用域外的枚举数?

c++ - 阻止库调用 getenv?

c++ - 不包括 boost 信号调用

c++ - 是否有可能在 C++ 中获取类型别名的名称?

java - Android OpenGLES 骨骼动画问题

iphone - 在 iOS 中显示像素矩阵的最佳方式

c++ - 是否可以在 [win-builder](http ://win-builder. r-project.org/) 上构建一个使用 Rcpp 和 Boost.Thread 的 R 包?

C++,成员地址

c++ - 为什么 "virtuality"方法在 C++ 中隐式传播?

python - 使用来自 2 个 numpy 矩阵的数据绘制直方图