Wednesday, March 30, 2016

C++ get array size with template


#include <iostream>

using namespace std;

template <typename T, unsigned int S>
unsigned int array_size(const T (&)[S])
{
    return S;
}

int main()
{
    char a[] = "Hello, world!";
    unsigned int s = array_size(a);
    cout << s << endl;
    return 0;
}


The output of the program is 14.

T(&)[S] is the type of the passed in parameter, i.e. T (&in)[S], where "in" is the reference of the array "a[14]" in our case. When doing the type deduction, the compiler will match T with char and S with 14. 

No comments:

 
Get This <