1

我想知道以下两个实现是否会产生完全相同的东西并具有相同的性能,无论我使用什么编译器:

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];
};

在第一个中,由于循环中使用的 TSIZE 是一个模板参数,因此几乎可以保证编译器会在需要时展开循环。如果循环在第一种情况下展开,是否会在第二种情况下展开(唯一的区别是 TSIZE 存储在静态常量中)?

非常感谢你。

4

2 回答 2

5

Whether the compiler will perform the optimization or not is different from whether it will treat the value as a compile time constant. In your particular example, and because the static const has not been defined anywhere, if the linker did not complain it means that the compiler only used it as a const-expression (compile time constant). Also note that if the compiler was not considering size_const as a const-expression, then the line T _data[size_const] (I am assuming you lost the T on the copy) would not compile.

Any odr-use (use other than as a compile time constant) of the static member would require a definition.

于 2012-08-03T20:50:08.010 回答
0

从逻辑上讲,编译器确实有足够的信息来进行您所描述的优化,但是它是否真的会这样做是非常依赖于实现的,我不希望它得到普遍支持

于 2012-08-03T20:46:47.997 回答