problem with sizeof operator

前端 未结 6 1834
遥遥无期
遥遥无期 2020-12-01 15:24

As i want to find array size dynamically in function, i used sizeof operator. But i got some unexpected result. here is one demo program to show you, what i want to do.

6条回答
  •  情书的邮戳
    2020-12-01 16:02

    To prevent this type of accidental misuse of sizeof, you can define a function which only works on arrays:

    template
    int array_size(T (&)[N]) {
      return N;
    }
    

    If you use this in your code, you'll see a compiler error when applied to S1, as it is not an array. Plus, it's shorter and a bit more explicit than sizeof array / sizeof array[0] (using the size of the first item means you don't have to repeat the array type).

    This also already exists in Boost in a more general form (accepting anything with a size method, such as std::vector).

提交回复
热议问题