I know this question asked many times and I’m not asking how to do it because i did that at compile-time. My question is how it works because that is what i don’t understand.
When passing a char[] to a function it looses its information and become char* and because of that we can not get size of character array at compile time using template, so i tried and passed the string itself and it worked:
template <int N> inline int arr_len(const char (&)[N]) { return N - 1; }
#define STR "this is an example!"
const char *str_ptr = STR;
int main()
{
int array_size = arr_len(STR);
}
I tested this code with VC++ 2008, Intel C++ 12 and GCC 4.7 and it works.
By passing the string itself the compiler sees it as const char[] – at least that what i think – and he able to get the string size, How is that possible?
String literal type is an array, not a pointer. So, when you pass it directly to a function that takes array by reference, it doesn’t decay to a pointer.