Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template code optimization for specific values of non-type parameters.

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?

like image 697
DyingSoul Avatar asked Dec 27 '22 19:12

DyingSoul


2 Answers

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.

like image 93
Björn Pollex Avatar answered Jan 13 '23 20:01

Björn Pollex


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.

like image 25
gwiazdorrr Avatar answered Jan 13 '23 19:01

gwiazdorrr