Loop using a template variable not working?

时间:2015-10-31 00:00:03

标签: c++ for-loop compiler-errors

Here is my situation: I made a function called MyFunction MyFunction accepts two arrays using parameter definitions template<std::size_t N1, std::size_t M1, std::size_t N2, std::size_t M2>. Then I made MyFunction as follows: void MyFunction(double (&W)[N1][M1],double (&TD)[N2][M2]){ And in MyFunction I have a for loop like this for(int i; i<N1; i++){...}. It won't compile and there is also has a warning saying: warning: comparison between signed and unsigned integer expressions. I don't know what this warning means. If anybody knows why this is happening please help. :)

1 个答案:

答案 0 :(得分:1)

std::size_t is an unsigned type and int is a signed type. The warning is very clear: you are trying to compare i, which is of a signed type, with N1, which is of an unsigned type. And you presumably have -Werror turned on or something like that. The reason why this warning exists is that you can get counterintuitive results. For example, -1 < (std::size_t)(0) is most likely false, since -1 will most likely be converted to std::size_t and end up as a large positive value. (Technically, this happens because the relational operators perform the usual arithmetic conversions, which favour unsigned types over signed types of equal or lesser width.) However, many people also disable this warning, because the use of an int loop control variable is extremely common and usually benign. Just make sure you can't get any negative numbers.