预处理程序指令#if和非类型模板参数

时间:2012-02-13 17:29:33

标签: c++ templates c-preprocessor

相关:

我可以这样做吗?

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

2 个答案:

答案 0 :(得分:7)

这个确切的代码不起作用,因为宏替换发生在模板实例化之前。换句话说,到编译器实际开始使用参数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;
} ;

希望这有帮助!

答案 1 :(得分:6)

没有。在评估模板之前运行proprocessor。请改用模板专业化。

template<int N> union Vector {
  float e[N];
};

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

// etc