Re: Is this legal C++?
arrowtackett <arrowtackett@gmail.com> writes:
If this is indeed legal C++, this is a very nice way for a function
to accept N-dimensional vectors.
I don't see a problem with the principle, but
template<typename A>
unsigned int getDimension(A const &)
{
return 0;
}
template<typename A>
unsigned int getDimension(std::vector<A> const &vec)
{
assert(!vec.empty());
return getDimension(vec[0])+1;
}
is a simpler way to do it.
And this does it at compile time, which is even nicer:
#include <iostream>
#include <ostream>
#include <vector>
template <typename T>
struct vectorDimension
{
enum
{
value = 0
};
};
template <typename T>
struct vectorDimension< std::vector<T> >
{
enum
{
value = vectorDimension<T>::value+1
};
};
int main()
{
typedef std::vector<double> V1;
typedef std::vector<std::vector<double> > V2;
typedef std::vector<std::vector<std::vector<double> > > V3;
std::cout << "The dimension of the vector is: "
<< vectorDimension<V3>::value
<< '\n';
}
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]