Question

I wonder if the two following implementations will produce exactly the same thing with the same performances whatever the compiler I use :

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

In the first one, as TSIZE used in the loop is a template parameter, it is almost guaranteed that the compiler will unroll the loop if needed. If the loop is unrolled in the first case, would it be unrolled in the second case (the only difference is that TSIZE is stored in a static const) ?

Thank you very much.

Was it helpful?

Solution

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.

OTHER TIPS

Logically a compiler does have enough information to do the optimization you are describing however whether it will actually do it is extremely implementation-dependent and I wouldn't expect it to be universally supported

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top