I'm programming with C++ on Ubuntu 12.04 and g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3.
I have a templated Vector class
template <typename type, int length>
class Vector {
// Implementation
};
which has length components of type type.
I use this class in some other class, which is also templated. This class takes the number of elements to use for its vectors as a template argument (dim).
This argument is either 2 or 3. I have to do special things, if dim == 3, so I wrote more or less often things like this:
if (dim == 3) {
// do special things here
}
I thought, when the class is called with parameter 2, the compiler will see, that the condition is never true and will not translate it and vice versa, if the parameter is 3, the compiler will see, that the condition is never false and will translate everything and optimize out the if.
When compiling with -O0 I get no warnings, but when switching on -O3 I get the warning array subscript is above array bounds pointing to lines like this one
Vector<pr, dim> v;
v[0] = ...
v[1] = ...
if (dim == 3) v[2] = ...
where pr is a type, given as a parameter.
I don't understand, why I get the warnings, because: if dim == 2, the assignment will never be executed and if it's 3, the assignment does not cause any problems.
I thought all the time, templating will work like this: the compiler takes the template code and replaces all occurrences of parameters with the parameters given and then treats this, as it were a simple class.
My question now is, why is the compiler warning me about things, it knows, that they will never happen?
And why do I get the warnings only, when compiling with optimizations?
dimand the dimensionality ofvso it doesn't realize that the two are linked.