簡體   English   中英

C ++:如何在類成員中使用未命名的模板參數?

[英]C++: How to use unnamed template parameters in class members?

我正在創建一個簡單的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)

你知道如何解決這個問題嗎?

提前致謝。

模板參數名稱是每個模板聲明的“本地”。 沒有什么可以阻止您分配名稱。 如果您以后需要引用該參數(例如將其用作類的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_;
};

你可以在課外定義它,例如:

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

只是不要忘記,在常見情況下, 模板只能在頭文件中定義

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM