kl*****@gmail.com wrote:
I would like to count the nesting level in template classes. How can I
make the following work?
#include <assert.h>
template <class T>
class A {
public:
A() {
// what goes here?
Nothing. Initialise your 'data' in the initialiser list.
}
unsigned nesting_level;
Shouldn't this be 'enum' or 'static'? I think you need to initialise
the 'nesting_level' here from 'T's "nesting_level" if any.
Is this homework?
Try to create a template to "get the nesting level" and implement it so
that it returns 0 for any classes except A and returns A's nesting level
for the A class (template).
For the spoiler, look several pages below my signature. If this is in
fact your homework and you value education, don't look.
T* data;
};
int main() {
A<int> one;
A< A<int> > two;
assert(one.nesting_level==1);
assert(two.nesting_level==2);
}
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
#include <assert.h>
template <class T> struct get_n_l { enum { value = 0 }; };
template <class T>
class A {
public:
A() : data(0) {}
enum { nesting_level = get_n_l<T>::value + 1 };
T* data;
};
template <class T> struct get_n_l <A<T> > {
enum { value = A<T>::nesting_level };
};
int main() {
A<int> one;
A< A<int> > two;
assert(one.nesting_level == 1);
assert(two.nesting_level == 2);
}