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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…