0
template<int n>
struct Numberim{
     enum{ value = Numberim<n-1>::value + n };
};

template<>
struct Numberim<0>{
     enum{ value = 0 };
};

this is a simple tmp example,and it's ok;

template<int n>
class Numberim{
     enum{ value = Numberim<n-1>::value + n };
};

template<>
class Numberim<0>{
     enum{ value = 0 };
};

I use g++ to compile,and it complains...however, as far as I know, struct and class is treated nearly in the same way.just like this"In C++, the only difference between a struct and a class is that struct members are public by default, and class members are private by default."

So, what's the difference between them here in earth?

josephthomas
  • 3,256
  • 15
  • 20
Eric.Q
  • 703
  • 1
  • 9
  • 21

3 Answers3

3

The difference will be same as it would be for typically class vs struct. Your "value" will be public for your first example (using struct) and private for your second example (using class).

For a reference on the difference between a class and a struct, please see What are the differences between struct and class in C++.

Community
  • 1
  • 1
josephthomas
  • 3,256
  • 15
  • 20
0

Concrete class Numberim<1> is not related to concrete class Numberim<0>.

Thus, having one class refer to the other’s definition of value works when value is public, which it is for the struct, but not when value is private, which it is for the class.

You can use the friend mechanism, or you can make value public, or you can, much more simply, do this:

template<int n>
class Numberim{
    enum{ value = n*(n+1)/2 };
    // And whatever else you want in here. 
};
Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
0

The difference is still the same, when it tries to compile Numberim<n-1>::value with n=1 it tries to use the template specialization. However, since value is private member of Numberim<0> (as the class member variables are private by default) it gives the compiler error.

Naveen
  • 74,600
  • 47
  • 176
  • 233