I wondered if I could auto deduce the size of an array, which is passed as a template parameter, without (explicitly) passing its size.
The following code both compiles warning-less on g++ 4.8 and clang++ 3.3 (using -std=c++11 -Wall).
#include <iostream> template<const int* arr> struct array_container { static constexpr int val = arr[1]; array_container() { std::cout << val << std::endl; } // static constexpr int arr_size = ??; }; constexpr int one[] = { 1 }; constexpr int two[] = { 1, 2 }; int main() { // array_container<one> array_one; array_container<two> array_two; // (void) array_one; (void) array_two; return 0; } However, if I remove the two comment signs in main(), I get an out of bound error with both compilers.
Now, this is cool. Somehow the compiler knows the size of the array, though the type of const int* arr is a pointer. Is there any way to get the size of arr, e.g. to complete my comment in array_container?
Of course, you are not allowed to
- Use any macros
- Store the size in arr (e.g. passing an std::array as template parameter:
constexpr std::array<int, 1> one = { 1 }, or using an end marker like'\0'in strings) - Use an additional template parameter for the size that can not be auto deduced (
array_container<1, one> array_one).
array_container<decltype(arr_a), arr_a>::sizeis acceptable? :p