Consider the following simple function
void foo_rt(int n) {
for(int i=0; i<n; ++i) {
// ... do something relatively cheap ...
}
}
If I know the parameter n at compiletime, I can write a template version of the same function:
template<int n>
void foo_ct() {
for(int i=0; i<n; ++i) {
// ... do something relatively cheap ...
}
}
This allows the compiler to do things like loop unrolling, which increases speed.
But assume now that I sometimes know n at compiletime and sometimes only at runtime. How can I implement this without maintaining two versions of the function? I was thinking something along the lines:
inline void foo(int n) {
for(int i=0; i<n; ++i) {
// ... do something relatively cheap ...
}
}
// Runtime version
void foo_rt(int n) { foo(n); }
// Compiletime version
template<int n>
void foo_ct() { foo(n); }
But I am not sure if all compilers are smart enough to deal with this. Is there a better way?
EDIT:
Clearly, one solution that will work is to use macros, but this I really want to avoid:
#define foo_body \
{ \
for(int i=0; i<n; ++i) { \
// ... do something relatively cheap ... \
} \
}
// Runtime version
void foo_rt(int n) foo_body
// Compiletime version
template<int n>
void foo_ct() foo_body
I’ve done this before, using a
integral_variabletype andstd::integral_constant. This looks like a lot of code, but if you look again, it’s actually only a series of four very simple pieces, one of which is merely demo code.