Is this legal C++?
Below is a small piece of code that I'm curious about. It is a
recursive template function that accepts a vector of any dimension.
The function returns the dimension of the vector passed into it. It
seems that the typename parameter "A" is allowed to be a template
itself. This code doesn't give me any warnings, but Is this legit C+
+? I had never seen this before, and I have just recently discovered
this by accident. If this is indeed legal C++, this is a very nice
way for a function to accept N-dimensional vectors.
// file.cpp
#include <iostream>
#include <vector>
using namespace std;
template<typename A> int getDimension(const vector<A> &, int = 0);
template<typename A> int getDimension(const A &, int);
template<typename A>
int getDimension(const vector<A> &vec, int dims = 0) {
++dims;
int totalDims = getDimension(vec[0], dims);
return totalDims;
}
// Overloaded function that is called when the typename
// parameter is not a vector (the last recursive iteration)
template<typename A>
int getDimension(const A &vec, int dims) {
return dims;
}
int main() {
typedef vector<double> V1;
typedef vector<vector<double> > V2;
typedef vector<vector<vector<double> > > V3;
V3 vec3D(2, V2(3, V1(4, 0.0)));
int dim = getDimension(vec3D);
cout << "The dimension of the vector is: " << dim << endl;
return 0;
}
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]