【问题标题】:Preprocessor directive #if and non-type template parameters预处理器指令#if 和非类型模板参数
【发布时间】:2012-03-05 02:54:11
【问题描述】:

相关:

我可以这样做吗?

template <int N> union Vector
{
  float e[ N ] ;
  // If N is 3, define x,y,z components
  #if N==3
  struct { float x,y,z ; } ;
  #elif N==2
  struct { float x,y ; } ;
  #endif
} ;

// use
int main()
{
  Vector<2> xy ;
  xy.e[ 0 ] = 5 ;
  xy.e[ 1 ] = 2 ;
  xy.x = 2 ;

  Vector<3> xyz ;
  xyz.z = 4 ;
}

【问题讨论】:

    标签: c++ templates c-preprocessor


    【解决方案1】:

    没有。在评估模板之前运行处理器。请改用模板特化。

    template<int N> union Vector {
      float e[N];
    };
    
    template<> union Vector<3> {
      float e[3];
      struct { float x, y, z; };
    };
    
    // etc
    

    【讨论】:

      【解决方案2】:

      这个确切的代码不起作用,因为宏替换发生在模板实例化发生之前。换句话说,当编译器实际开始使用参数 N 实例化模板时,预处理器已经完成了条件包含。此外,预处理器没有关于模板是什么或 N 是模板参数的语义概念——它只是将 N 视为预处理器标记。

      如果想得到这个效果,可以使用模板特化:

      template <int N> union Vector
      {
        float e[ N ] ;
      };
      
      template <> union Vector<3>
        float e[ 3 ] ;
        float x, y, z;
      } ;
      
      template <> union Vector<2>
        float e[ 2 ] ;
        float x, y;
      } ;
      

      希望这会有所帮助!

      【讨论】:

      • 活到那个用户ID,嗯:)
      猜你喜欢
      • 2012-08-14
      • 2011-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-07
      • 2012-06-08
      • 1970-01-01
      相关资源
      最近更新 更多