【问题标题】:Struct with template variables in C++C++中带有模板变量的结构
【发布时间】:2011-01-27 17:47:22
【问题描述】:

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

我可以执行以下操作吗?

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

我正在尝试做的是一个基本的模板版本:

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

如果我使用类而不是结构,看起来它可以工作,那么 typedef 结构不可能吗?

【问题讨论】:

    标签: c++ class templates struct


    【解决方案1】:

    问题是你不能模板化 typedef,也没有必要在 C++ 中对结构进行 typedef。

    以下将满足您的需要

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

    【讨论】:

    • +1 用于解释您的代码和@monkeyking 的代码之间的区别。
    【解决方案2】:
    template <typename T>
    struct array {
      size_t x;
      T *ary;
    };
    

    【讨论】:

      【解决方案3】:

      你不需要为类和结构做一个显式的typedef。你需要typedef 做什么?此外,template&lt;...&gt; 之后的 typedef 在语法上是错误的。只需使用:

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

      【讨论】:

      • 嗯,你的意思是把它放在 struct 之后吗?
      【解决方案4】:

      您可以模板化结构和类。但是,您不能对 typedef 进行模板化。所以template&lt;typename T&gt; struct array {...}; 有效,但template&lt;typename T&gt; typedef struct {...} array; 无效。请注意,在 C++ 中不需要 typedef 技巧(在 C++ 中,您可以使用没有 struct 修饰符的结构)。

      【讨论】:

        【解决方案5】:

        标准说(在 14/3。对于非标准的人,类定义主体(或一般声明中的类型)后面的名称是“声明符”)

        在模板声明、显式特化或显式实例化中,声明中的 init-declarator-list 最多应包含一个声明符。当这样的声明用于声明类模板时,不允许使用任何声明符。

        像安德烈表演那样做。

        【讨论】:

          【解决方案6】:

          从其他答案来看,问题在于您正在模板化 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
              }
          }
          

          【讨论】:

            【解决方案7】:

            语法错误。 typedef 应该被删除。

            【讨论】:

              【解决方案8】:

              看起来@monkeyking 正在尝试使它更明显的代码如下所示

              template <typename T> 
              struct Array { 
                size_t x; 
                T *ary; 
              };
              
              typedef Array<int> iArray;
              typedef Array<float> fArray;
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 2014-12-22
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2013-01-22
                • 1970-01-01
                相关资源
                最近更新 更多