Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need to use scope resolution in template inheritance?

If I work with classes, everything is just fine:

struct Base1 {
  int value;
  Base1(int value) : value(value) { }
};

struct Test1 : public Base1 {
  int getValue() { return value; }  
  Test1(int value) : Base1(value) { }
};

but with templates scope resolution is needed:

template <typename T>
struct Base {
  T value;
  Base(T value) : value(value) { }
};

template <typename T>
struct Test : public Base<T> {
  typedef Base<T> parent;
  T getValue() { return parent::value; }  // why do I need to use parent:: here?
  Test(T value) : parent(value) { }
};

Without the scope resolution I receive error 'value' was not declared in this scope (gcc compiler used). Why?

like image 646
Jan Turoň Avatar asked Dec 02 '25 05:12

Jan Turoň


2 Answers

Because the compiler is not aware that value is dependent on the template argument. As such, it attempts to resolve it during the first pass (prior to instantiating the template), and fails.

The two options are to use the scoping resolution, as you have, or use this->value. Since this is always a dependent name, this will force the evaluation to occur during the second pass.

See http://ideone.com/07odY

Edit: And as to the why it needs to be done at all:

While Test<T> derives from Base<T>, due to template specialization you could make Base<std::string> (for example) be totally different than the normal Base<T>, and not have a member named value, or it could be of a different type, or anything. By forcing it to be a dependent name, the compiler is forced to wait until it knows the actual type involved before checking.

like image 126
Dave S Avatar answered Dec 03 '25 19:12

Dave S


Because there is no other way to tell the compiler (since it is not defined within Tests body) that value is a dependent name. You are forcing the compiler to say that "Okay! Believe me when I say that there is such a member value for the type T."

like image 28
dirkgently Avatar answered Dec 03 '25 20:12

dirkgently



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!