C ++:如何在类成员中使用未命名的模板参数? [英] C++: How to use unnamed template parameters in class members?

查看:159
本文介绍了C ++:如何在类成员中使用未命名的模板参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个简单的Matrix类. 我正在尝试添加一个未命名的模板参数,以确保它与整数类型一起使用

I am creating a simple Matrix class. I am trying to add an unnamed template parameter to make sure it is used with integral 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 the 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 ++返回以下错误

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 issue?

谢谢.

推荐答案

模板参数名称对于每个模板声明都是本地的".没有什么可以阻止您分配名称的.如果以后需要引用该参数(例如将其用作类的template-id中的参数),则确实必须执行该操作.

Template parameter names are "local" to each template declaration. Nothing prevents you from assigning a name. Which you indeed must do if you need to refer to that parameter later (such as using it as an argument in the template-id of the class).

因此,尽管您在类定义中有此定义:

So, while you have this in the 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 e.g. like this:

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)
{};

请不要忘记,在通常情况下,模板只能在头文件中定义.

Just do not forget that under common circumstances, templates can only be defined in header files.

这篇关于C ++:如何在类成员中使用未命名的模板参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆