Related:
- Reason for using non-type template parameter instead of regular parameter?
- What is angle brackets for argument values, and what is it used for?
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. 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.
If you want to get this effect, you can use template specialization:
Hope this helps!