Do modern compilers optimize multiplication by 1 and -1

二次信任 提交于 2020-01-02 14:01:23

问题


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


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/22279635/do-modern-compilers-optimize-multiplication-by-1-and-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!