Vin*_*ent 1 c++ optimization templates compilation loop-unrolling
我想知道无论我使用哪种编译器,以下两个实现是否会产生完全相同的性能:
template<class T, unsigned int TSIZE> MyClass1
{
static const unsigned int size_const = 0;
public:
inline void Loop()
{
for(unsigned int i = 0; i < TSIZE; ++i) {
/* DO SOMETHING ON DATA */
}
}
T _data[TSIZE];
};
template<class T, unsigned int TSIZE> MyClass2
{
static const unsigned int size_const = TSIZE;
public:
inline void Loop()
{
for(unsigned int i = 0; i < size_const; ++i) {
/* DO SOMETHING ON DATA */
}
}
T _data[size_const];
};
Run Code Online (Sandbox Code Playgroud)
在第一个中,由于循环中使用的TSIZE是模板参数,因此几乎可以保证编译器将根据需要展开循环.如果循环在第一种情况下展开,它是否会在第二种情况下展开(唯一的区别是TSIZE存储在静态const中)?
非常感谢你.
编译器是否执行优化不同于它是否将值视为编译时常量.在您的特定示例中,并且因为静态const尚未在任何地方定义,如果链接器没有抱怨,则意味着编译器仅将其用作const表达式(编译时常量).另请注意,如果编译器没有考虑size_const作为const表达式,那么该行T _data[size_const](我假设您丢失T了副本)将无法编译.
静态成员的任何使用(使用除了作为编译时间常量之外)都需要定义.