icosahedron wrote:
Is there a way to determine if a parameter to a function is a constant
(e.g. 2.0f) versus a variable? Is there some way to determine if this
is the case? (Say some metaprogramming tip or type trait?)
I have a function with an if statement, that I would like to optimize
away somehow. I was hoping the compiler would do it for me, but it
doesn't seem to.
Please post the code you want to change. So far your
question does not make sense. If your function is declared
so that you may pass a constant to it, then the argument is
passed by value or by a reference to const.
Even if you could determine where the argument originated,
how would it help you? What kind of optimization are you
trying to accomplish?
template <typename Element, int N>
float scale( Element (&array)[N], Element scale, int index )
{
if( index == 0 ) {
return array[ 0 ] * scale;
}
else {
return array[ index ];
}
}
int main( void )
{
float test_array[ 5 ] = { 3.0f, 2.0f, 1.0f, 0.0f, -1.0f };
int i = 0;
cout << scale( test_array, 3.0f, 0 ) << endl;
cout << scale( test_array, 3.0f, i ) << endl;
return 0;
}
Okay, so I would like to optimize the case when a 0 is passed into
scale, so that the if will automatically recognize it's a constant and
return array[index] * scale. When a variable is passed, I can
understand the compiler keeping the if. If a constant is passed, I
would have thought that the if would be optimized away, but that
doesn't seem to be the case.
So, what I would like to do is something similar to using
boost::mpl::if_c would do with a type trait or something that could
tell if index were a constant passed or a variable.
I know this is probably not doable. I was just asking in the event
there were something I was unaware of.
Thanks,
Jay