簡體   English   中英

C++ 中帶有模板變量的結構

[英]Struct with template variables in C++

我在玩模板。 我不是要重新發明 std::vector,而是要掌握 C++ 中的模板化。

我可以執行以下操作嗎?

template <typename T>
typedef struct{
  size_t x;
  T *ary;
}array;

我想要做的是一個基本的模板化版本:

typedef struct{
  size_t x;
  int *ary;
}iArray;

如果我使用類而不是結構,看起來它可以工作,那么使用 typedef 結構是不可能的嗎?

問題是你不能對 typedef 進行模板化,也不需要在 C++ 中對結構進行 typedef。

以下將做你需要的

template <typename T> 
struct array { 
  size_t x; 
  T *ary; 
}; 
template <typename T>
struct array {
  size_t x;
  T *ary;
};

你不需要為類和結構做一個顯式的typedef 你需要typedef做什么? 此外, template<...>之后的typedef在語法上是錯誤的。 只需使用:

template <class T>
struct array {
  size_t x;
  T *ary;
} ;

您可以對結構和類進行模板化。 但是,您不能對 typedef 進行模板化。 所以template<typename T> struct array {...}; 有效,但template<typename T> typedef struct {...} array; 才不是。 請注意,在 C++ 中不需要 typedef 技巧(您可以在 C++ 中使用沒有struct修飾符的struct )。

標准說(在 14/3。對於非標准的人,類定義主體(或一般聲明中的類型)后面的名稱是“聲明符”)

在模板聲明、顯式專業化或顯式實例化中,聲明中的 init-declarator-list 最多應包含一個聲明符。 當這樣的聲明用於聲明類模板時,不允許使用聲明符。

像安德烈秀那樣做。

語法錯誤。 應該刪除typedef

從其他答案來看,問題在於您正在對 typedef 進行模板化。 做到這一點的唯一“方法”是使用模板化類; 即,基本模板元編程。

template<class T> class vector_Typedefs {
    /*typedef*/ struct array { //The typedef isn't necessary
        size_t x; 
        T *ary; 
    }; 

    //Any other templated typedefs you need. Think of the templated class like something
    // between a function and namespace.
}

//An advantage is:
template<> class vector_Typedefs<bool>
{
    struct array {
        //Special behavior for the binary array
    }
}

看起來@monkeyking 正在嘗試使它更明顯的代碼如下所示

template <typename T> 
struct Array { 
  size_t x; 
  T *ary; 
};

typedef Array<int> iArray;
typedef Array<float> fArray;

暫無
暫無

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

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