Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
78 views
in Technique[技术] by (71.8m points)

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

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

template<typename T, size_t N>
size_t arraylen( T(&)[N] )
{ return N; }

I'd like to take this idea one step further.

struct Foo
{
   template< typename T, size_t N >
   Foo( /* ??? */ ) : ptr(?), size(?) { }

   char* ptr;
   size_t size;
};

int main()
{
   Foo foo("test");

   const char bar[] = "test2";
   Foo foo2(bar);


   const char* baz = bar;
   Foo foo3(baz); // compiler error.
}

However, for the life of me I can't get the syntax to compile. I think part of what I'm missing is I don't really understand what the T(&)[N] means.

What does T(&)[N] mean?

How can I allow access to array's address while still grabbing its size with templates?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...