Question

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)?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Although in this case compiler do optimization for you, in more complex cases it may be necessary to write different variants of optimal code for different template arguments. Hence you may use template specialization to do it:

template<int sign>
inline int add_sign(int x);

template<>
inline int add_sign<-1>(int x) {
    return -x;
}

template<>
inline int add_sign<1>(int x) {
    return x;
}

With such fully specialized function you are not required to write explicit instantiations for it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top