Converting from T[][]...[] to T**...*

Just for the fun of it, I thought I would implement my own any class. When I finished, everything worked except for

any a="Hello World!"

The reason it didn't work is the type of the string literal is const char[13], and assigning const char[13] to another of that type is illegal. So, I was wondering if there was any template metaprogramming magic that could convert from T[][]...[] (any number of []'s) to T**...*, where the number of asterisks is the same as the number of brackets. And yes, I could just specialize for T[] and explicitly convert it to T*, but then it doesn't work for the rare use of T[][], or even T[][][].
Last edited on
Your assignment operator should be one of:

any& operator = ( const char* s ); any& operator = ( const std::string& s );

Good luck!
But that only works for character arrays... What if someone used it like this:

1
2
int i[]={1,1,2,3,5,8,13};
any a=i;

Or like this:

1
2
int i[][]={{1,1,2,3,5,8,13},{2,3,5,7,11,13,17},{3,1,4,1,5,9,2}};
any a=i;

An any class should be able to contain anything.
any& operator = ( const int* xs );

Have you looked at Boost Any?
I looked at boost any for help whenever I was stuck, although it's a bit difficult to read because of all the extra stuff meant to give it compatibility.

Actually, I guess that could work.

1
2
template<class T>
any& operator=(T* value);

If T was something like int[][][][] it would implicitly convert it to a pointer to int[][][] which is assignable. Thanks!
Last edited on
For array dimensions, you have to play tricky with templates. For example, remember the old (or new?) trick of getting an array's length:

1
2
3
// Some variation of the following is common:
template <typename T, size_t N>
size_t SizeOfArray( T (&)[ N ] ) { return N; }

http://www.cplusplus.com/forum/general/19458/#msg101474

You can, of course, extend this to multiple dimensions.

If you are using C++0x/11, I believe you can even do it for arbitrary dimensions. (But don't hold me on that! I'm probably wrong!)
Topic archived. No new replies allowed.