我不明白我遇到的这个例子:
int Multiply(int x, int m){ return x * m;} template<int m> int MultiplyBy(int x){ return x * m;} int a,b; a = Multiply(10,8); b = MultiplyBy<8>(10);
In the above example the template function is faster than the simple function because the compiler knows that it can multiply by a power of 2 by using a shift operation. x*8 is replaced by x << , which is faster. In the case of the simple function, the compiler doesnt know the value of m and therefore cannot do the optimization unless the function can be inlined.
据我了解,模板可以优化的原因是因为编译器在编译时知道参数 (8) 的值,而简单函数直到运行时才知道 x(或 m)的值-时间。那么内联简单函数将如何改变这一事实呢?内联不提供参数值的任何运行时知识??
最佳答案
Inlining doesn't provide any run-time knowledge of the argument value??
内联本身没有。但是,由于第二个参数是编译时常量,编译器可以将该常量传播到内联函数中。
由于第一个参数也是一个编译时常量,所以整个
a = Multiply(10,8);
可以替换为
a = 80;
事实上,当我打开优化时,这正是我的编译器 (gcc 4.7.2) 所做的。
关于c++ - 模板和内联优化乘法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15532209/