template <bool flag>
class foo
{
public:
int bar()
{
if(flag)
{
// stuff
}
}
};
When the compiler compiles this class, it replaces the flag parameter by true or false. Then we have if(true) ( or if(false) ). Then, the if clause checks against a constant expression and WILL BE REMOVED at compile time. Can I expect compilers to behave like this?
No you can't. Any optimization is completely up to the compiler. Since you are using templates, you should write a specialization for both cases of flag
.
Optimizations are compiler-specific. Why don't you create release build and step through disassembly?
Still, this is not idiomatic way to do that. You should either use template specialization or method overloading. They both provide compile-time resolving. So, in this case I would prefer the latter:
#include <type_traits>
template <bool flag>
class foo
{
public:
int bar()
{
_bar(std::integral_constant<bool, flag>())
}
private:
int _bar(std::true_type)
{
// stuff
}
int _bar(std::false_type)
{
// empty
}
};
EDIT: this requires C++0x, but can be easily translated to C++98 by including boost/type_traits
and changing std::
directives to boost::
. And, of course, it will require boost libraries.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With