简体   繁体   English

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

[英]Preprocessor directive #if and non-type template parameters

Related: 有关:

Can I do this? 我可以这样做吗?

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

This exact code won't work, because macro substitution occurs before template instantiation occurs. 这个确切的代码不起作用,因为宏替换发生在模板实例化之前。 In other words, by the time that the compiler is actually going to start instantiating the template with the argument N, the preprocessor has already done its conditional inclusion. 换句话说,到编译器实际开始使用参数N实例化模板时,预处理器已经完成了条件包含。 Moreover, the preprocessor has no semantic idea of what a template is or that N is the template argument - it just treats N as a preprocessor token. 此外,预处理器没有模板是什么的语义概念或N是模板参数 - 它只是将N视为预处理器令牌。

If you want to get this effect, you can use template specialization: 如果要获得此效果,可以使用模板专门化:

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

Hope this helps! 希望这可以帮助!

No. The proprocessor is run before the templates are evaluated. 不会。在评估模板之前运行proprocessor。 Use template specialization instead. 请改用模板专业化。

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

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

// etc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM