S
suranap
I am looking at some examples of template metaprogramming, but I'm not
clear on some details of templates. In particular, what kinds of
computations will be performed at compile-time? Is it only arithmetic
on integers (+,-,*,/)?
1) When using a template, what kinds of operations are allowed within
the <>?
int x = Factorial<i-1>::value // what other operators are allowed
besides -?
2) Within an enum, what operators are allowed to compute a value at
compile-time?
enum { value = N * Factorial<N-1>::value }; // instead of *? Will other
datatypes work, like char or strings?
3) Will the value of an enum get propagated within the template body at
compile-time?
template<int N>
struct Example {
enum { value1 = N - 1 };
enum { value2 = value1 - 1 } ; // value2 needs value1 here
}
Example:
template<int N>
struct Factorial {
enum { value = N * Factorial<N-1>::value };
};
template<>
struct Factorial<1> {
enum { value = 1 };
};
// Example use
const int fact5 = Factorial<5>::value;
clear on some details of templates. In particular, what kinds of
computations will be performed at compile-time? Is it only arithmetic
on integers (+,-,*,/)?
1) When using a template, what kinds of operations are allowed within
the <>?
int x = Factorial<i-1>::value // what other operators are allowed
besides -?
2) Within an enum, what operators are allowed to compute a value at
compile-time?
enum { value = N * Factorial<N-1>::value }; // instead of *? Will other
datatypes work, like char or strings?
3) Will the value of an enum get propagated within the template body at
compile-time?
template<int N>
struct Example {
enum { value1 = N - 1 };
enum { value2 = value1 - 1 } ; // value2 needs value1 here
}
Example:
template<int N>
struct Factorial {
enum { value = N * Factorial<N-1>::value };
};
template<>
struct Factorial<1> {
enum { value = 1 };
};
// Example use
const int fact5 = Factorial<5>::value;