1

I can not access the member data "value" defined in the template class from the specialized one. Why? Some one can help me? Thanks

template <class T>
class A {

public:

  int value;

  A() {
    value = 0;
  }

};


template <> class A<int> {

public:

  A() {
    value = 3;  // Use of undeclared identifier 'value'
    A::value = 3; // No member named 'value' in 'A<int>'
    this->value = 3; // No member named 'value' in 'A<int>'
  }

};
curiousguy
  • 8,038
  • 2
  • 40
  • 58
thewoz
  • 499
  • 2
  • 4
  • 23

1 Answers1

4

An explicit specialization is like a whole new thing. You can't access anything from the explicit specialization of A<int> in the primary template, because it's just like a totally different class.

But, it seems like you want to only specialize the constructor. In that case, you can do that:

template <> 
A<int>::A() {
    value = 3;  // ok
}

This works because you are only specializing the constructor, and the rest of the class is taken from the primary template.

Rakete1111
  • 47,013
  • 16
  • 123
  • 162
  • Thank you very much! all is now clear to me. But what is the point of do a explicit specialization if you can not access to the member of the primary template? – thewoz Dec 03 '18 at 08:44
  • 1
    @thewoz Well, explicit specialization is used when you need to do something different for a specific type. In general, you don't need anything from the primary template. If you do however need the same things in both, the normal technique is create a non-template base class that you then inherit from both the primary and the explicit specialization. – Rakete1111 Dec 03 '18 at 09:33
  • ok understood. The example is a simplification on what in reality I need. int value; should be T value; and beyond that to have a specialization of the constructor I will need a specialization of some function. – thewoz Dec 04 '18 at 10:32
  • @thewoz If they are doing something else, then yes. – Rakete1111 Dec 04 '18 at 10:49