Optimization of the template code for specific parameter values ​​other than type.

template <bool flag> class foo { public: int bar() { if(flag) { // stuff } } }; 

When the compiler compiles this class, it replaces the flag parameter with true or false. Then we have if (true) (or if (false)). Then, the if clause checks the constant expression and WILL BE DELETED at compile time. Can I expect compilers to behave like this?

+4
source share
3 answers

Optimizations are compiler specific. Why don't you build and disassemble?

However, this is not an idiomatic way to do this. You must either use specialized specialization or method overloading. They both provide a solution at compile time. 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 it can easily be converted to C ++ 98 by turning on boost/type_traits and changing the directives std:: to boost:: . And, of course, accelerator libraries will be required for this.

+2
source

No, you can’t. Any optimization is entirely up to the compiler. Since you use templates, you must write specialization for both cases of flag .

+6
source

Expect yes. I guess not. But how would you notice anyway?

Please note: you cannot create a template using false if you write code inside an if , which cannot be compiled when flag is false . Deletion of the test will be performed by the optimizer, which conceptually starts after the compiler has figured out what the code means in the first place.

+2
source

All Articles