gpt4 book ai didi

c++ - 模板中内联函数的好处

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:44:26 30 4
gpt4 key购买 nike

按照标准,C++中成员函数的内联定义等同于用inline关键字声明。记住这一点,我写的大部分模板只包含内联函数,因为这样代码就更短了(函数体也必须在标题中,以便可以从多个 .cpp 中使用 文件,因此可以说它只会减慢解析速度)。

(理智的)编译器现在会尝试内联所有函数吗?在实践中将内联成员函数定义为 inline 有什么好处吗(参见下面的示例)?从现在开始,我是否应该避免在模板中编写内联函数?

template <class Foo>
struct Bar {
inline bool IsThereBenefitInDoingThis()
{
return 10 < system("exit `wget -q -o - "
"http://stackoverflow.com/questions/23789353/ | grep yes | wc -l`");
}
};

最佳答案

一个简单的测试:

#include <math.h>
#include <stdio.h>

template <class T>
class Sine {
public:
#ifdef MAKEINLINE
inline T Eval(T x)
#else // MAKEINLINE
T Eval(T x)
#endif // MAKEINLINE
#ifdef PUTOUTSIDE
;
#else // PUTOUTSIDE
{
return T(sin(double(x)));
}
#endif // PUTOUTSIDE
};

#ifdef PUTOUTSIDE
template <class T>
#ifdef MAKEINLINE
inline T Sine<T>::Eval(T x)
#else // MAKEINLINE
T Sine<T>::Eval(T x)
#endif // MAKEINLINE
{
return T(sin(double(x)));
}
#endif // PUTOUTSIDE

int main(int argc, const char **argv)
{
printf("%g\n", Sine<float>().Eval(M_PI));
printf("%g\n", Sine<double>().Eval(M_PI));
return 0;
}

运行:

g++ Main.cpp -o testi -DMAKEINLINE -O1
g++ Main.cpp -o testn -O1
g++ Main.cpp -o testo -DPUTOUTSIDE -O1
g++ Main.cpp -o testoi -DMAKEINLINE -DPUTOUTSIDE -O1
diff testi testn
diff testi testo
diff testi testoi

揭示了 testitesto 之间的区别,所以只要 body 在里面,它是否被声明为 inline 似乎并不重要>,或者至少在这个简单的例子中和 g++ (GCC) 4.6.4 中。请注意,提高优化级别会内联该函数的所有版本,并且没有差异。

关于c++ - 模板中内联函数的好处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23789353/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com