If I write
template<int sign>
inline int add_sign(int x) {
return sign * x;
}
template int add_sign<-1>(int x);
template int add_sign<1>(int x);
Are most C++ compilers smart enough to optimize the multiplication by 1 or -1 into some faster operation (no-op or negation)?
Yes. This is part of a class of simple optimizations known as arithmetic local optimizations. For example 1 * x can be simplified statically to x, likewise -1 * x can be simplified to -x. Production compilers all do this and far more complex optimizations as well.
For g++, use g++ -S Foo.cc to view the assembler and determine whether the template has been optimized or not. For clang, take a look at this question. For Visual Studio, take a look at this question.
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