Use templates to get an array's size and end address

前端 未结 1 1670
执念已碎
执念已碎 2020-12-07 04:19

You can use templates to find the length of an array.

template
size_t arraylen( T(&)[N] )
{ return N; }

I\'

相关标签:
1条回答
  • 2020-12-07 04:38
    struct Foo
    {
       template< typename T, size_t N >
       Foo(T(&array)[N]) : ptr(array), size(N) { }
    
       const char* ptr;
       size_t size;
    };
    

    array is a reference to an array of N T's. The same is true of the original code, but the parameter isn't given a name.

    But this really isn't calculating the address at compile time. If you think about it, you'll realize this is impossible. If stack addresses were fixed, recursion (and many other algorithms) could never work.

    Note that the last line:

    Foo foo3(baz);
    

    still won't work because baz is a pointer not an array.

    0 讨论(0)
提交回复
热议问题