3

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?

Chris
  • 6,642
  • 7
  • 42
  • 55

3 Answers3

5

It's entirely possible. Try for example

template<int N, typename T, int M, typename U>
inline typename enable_if<is_deeper<T, U>::value, vec<N,T> >::type 
operator +(const vec<N,T>& v1, const vec<M,U>& v2) {
    return v1 + coerce(v2,v1);
}

template<int N, typename T, int M, typename U>
inline typename enable_if<is_deeper<U, T>::value, vec<M,U> >::type 
operator +(const vec<N,T>& v1, const vec<M,U>& v2) {
    return coerce(v1,v2) + v2;
}

Where is_deeper is something like

/* BTW what do you want to do if none is deeper? */
template<typename T, typename U>
struct is_deeper { static bool const value = false; };

template<typename T, int N, typename U>
struct is_deeper<vec<N, U>, T> { 
  static bool const value = true;
};

template<typename T, int N, typename U>
struct is_deeper<T, vec<N, U> > { 
  static bool const value = false;
};

template<typename T, int N, int M, typename U>
struct is_deeper<vec<M, T>, vec<N, U> > : is_deeper<T, U> 
{ };
Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
  • 2
    sometimes i use `mpl::true_` as `struct is_deeper, T> : mpl::true_ {};` and false likewise – Anycorn Sep 14 '10 at 21:10
  • Absolutely brilliant! Thank you! (BTW, if none is deeper - they're the same depth - it will get resolved to a more specialized + operator that adds each component) – Chris Sep 14 '10 at 22:26
  • 1
    Binary type traits should be avoided because they don't play well with memoization. This will result in O(Depth) new templates being generated for every pair of array types compared, which may go up to O(Depth^3). Better to define a single `depth` trait and compare the result. – Potatoswatter Sep 14 '10 at 22:38
  • @Potatoswatter good point about the memoization. Doing it by a `get_depth` and then comparing looks to me to be better here. But then `is_deeper` was just an example of what he can do :) – Johannes Schaub - litb Sep 14 '10 at 22:53
3

Template metaprogramming will set you free. I'm doing this at run-time, but it's evaluated at compile-time:

  #include <iostream>
#include <boost\static_assert.hpp>
using namespace std;

template<size_t Depth> class Vec
{
public:
 enum {MyDepth = Vec<Depth-1>::MyDepth + 1};
};

template<> class Vec<1>
{
public:
 enum {MyDepth = 1};
};

  BOOST_STATIC_ASSERT(Vec<12>::MyDepth == 12);
//  Un-commenting the following line will generate a compile-time error
//    BOOST_STATIC_ASSERT(Vec<48>::MyDepth == 12);

int main()
{
 cout << "v12 depth = " << Vec<12>::MyDepth;
}

EDIT: Included a boost static assert to demonstrate how this is evaluated at compile-time.

John Dibling
  • 99,718
  • 31
  • 186
  • 324
2

Partial specialization is very useful for introspection. Usually it's better to avoid inline functions with compile-time constant results. (C++0x might ease this a bit, but I'm not sure how much.)

First, your vec template looks a lot like boost::array/std::tr1::array/std::array, so I'll just call it array.

template< class ArrT >
struct array_depth; // in the general case, array depth is undefined

template< class ElemT, size_t N > // partial specialization
struct array_depth< array< ElemT, N > > { // arrays do have depth
    enum { value = 0 }; // in the general case, it is zero
};

template< class ElemT, size_t N1, size_t N2 > // more specialized than previous
struct array_depth< array< array< ElemT, N1 >, N2 > {
    enum { value = 1 + array_depth< array< ElemT, N1 > >::value }; // recurse
};

// define specializations for other nested datatypes, C-style arrays, etc.
// C++0x std::rank<> already defines this for C-style arrays
Potatoswatter
  • 134,909
  • 25
  • 265
  • 421
  • This is a good solution. Is there any difference between using 'static' class member / union with respect to either C++03 or C++0x? – Chubsdad Sep 15 '10 at 00:26
  • @Chubsdad I don't think C++0x has changed any `static` semantics. I prefer `enum` over `static const int` because you don't have to define it outside the class scope. Hmm, actually yes, C++0x extends the in-class initialization to other types… but it's still a bit pointless since the namespace-scope definition is still required. – Potatoswatter Sep 15 '10 at 01:45
  • @Chubsdad if you only ever read values from the static member and never rely on its address (by getting an lvalue and storing it into some reference or taking its address explicitly) you are not required to define a static data member though. An in-class initialized const integer suffices then (such a static data member is not considered "used" by the ODR). There are some edge cases that makes it "used" that can be surprising - for instance in `a ? lval1 : lval2` for both lvalues having the same type "uses" the lval's referent. But such cases are rare. – Johannes Schaub - litb Sep 15 '10 at 05:24
  • Johannes Schaub - litb: Oh!. Can you kindly give me the reference about this in the Standard (for my reference rather than anything else :)) – Chubsdad Sep 15 '10 at 05:30
  • @Chubsdad: Ah, it's under "classes" and under "static members"… this is not something they hid ;v) – Potatoswatter Sep 15 '10 at 06:09
  • @Potatoswatter: couldn't find anything which says it is OK to use such a static class member even if it is not defined – Chubsdad Sep 15 '10 at 07:48
  • @Chubsdad: 9.4.2/4: "… In that case, the member can appear in integral constant expressions. The member shall still be defined in a name- space scope **if it is used in the program**…" – Potatoswatter Sep 15 '10 at 09:25
  • I'd consider omitting that definition pretty bad form, though. There are enough problems with rvalues vs lvalues already; we don't need objects that syntactically can have an address taken only to cause a linker error. – Potatoswatter Sep 15 '10 at 09:34
  • @Potatoswatter: Yes. I agree. As litb mentioned, it is an edge case of 'used' – Chubsdad Sep 15 '10 at 10:01
  • @Chubsdad see http://stackoverflow.com/questions/1312241/using-a-static-const-int-in-a-struct-class/1312377#1312377 and http://stackoverflow.com/questions/578654/static-constant-class-members/578672#578672 . And the conditional-operator thing: http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#712 – Johannes Schaub - litb Sep 15 '10 at 19:47