Say you have a vector class that has a template length and type - i.e. vec<2,float>
. These can also be nested - vec<2,vec<2,vec<2,float> > >
, or vec<2,vec<2,float> >
. You can calculate how deeply nested one of these vectors is like this:
template<typename T>
inline int depth(const T& t) { return 0; }
template<int N, typename T>
inline int depth(const vec<N,T>& v) { return 1+depth(v[0]); }
The trouble is you won't know how deep it is until run-time, but you may need to know the depth at comile-time in order to do something like this:
// Do this one when depth(v1) > depth(v2)
template<int N, typename T, int M, typename U>
inline vec<N,T> operator +(const vec<N,T>& v1, const vec<M,U>& v2) {
return v1 + coerce(v2,v1);
}
// Do this one when depth(v1) < depth(v2)
template<int N, typename T, int M, typename U>
inline vec<M,U> operator +(const vec<N,T>& v1, const vec<M,U>& v2) {
return coerce(v1,v2) + v2;
}
You can't just throw in an "if" statement because (a) which is deeper affects the return type and (b) coerce() generates a build error if you try to coerce a nested vector to a less-nested one.
Is it possible to do something like this or am I pushed up against the limits of C++ templates?