Re: Is this legal C++?
arrowtackett wrote:
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.
No. It can be an *instance* of a class template because the result
of instantiation is an ordinary class.
template<typename A>
int getDimension(const vector<A> &vec, int dims = 0) {
++dims;
int totalDims = getDimension(vec[0], dims);
return totalDims;
}
template<typename A>
int getDimension(const A &vec, int dims) {
return dims;
}
That's a bit circuitous. Also, the vec[0] objects may not exist below
some level -- what you're really operating on is the type, so let's
express it that way:
#include <iostream>
#include <vector>
template<class>
struct VectorDimension {
static const int dimension = 0;
};
template<class A>
struct VectorDimension<std::vector<A> > {
static const int dimension = 1 + VectorDimension<A>::dimension;
};
/* The foregoing metafunction replaces your code, but it's still
convenient to have either or both of the functions below as
abbreviations in cases where all you need is a runtime value.
*/
template<class A>
int vectorDimension(const A&) {
return VectorDimension<A>::dimension;
}
template<class A>
int vectorDimension() {
return VectorDimension<A>::dimension;
}
int main() {
using namespace std;
typedef vector<double> V1;
typedef vector<vector<double> > V2;
typedef vector<vector<vector<double> > > V3;
V3 vec3D(2, V2(3, V1(4, 0.0)));
cout << "The dimension of the vector is: " << vectorDimension(vec3D) << endl;
cout << "The dimension of the type is: " << vectorDimension<V3>() << endl;
return 0;
}
Martin
--
Quidquid latine scriptum est, altum videtur.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]