2

In a situation like this, why can't I access the base class member x unqualified in the B1 case? Doesn't loook ambiguous to me…

template<class T>
struct A { T x; };

template<class T>
struct B1 : A<T> { T f() { return A<T>::x; } };

struct B2 : A<int> { int f() { return x; } };
1
  • didn't know of using A<T>::x before either Commented Apr 5, 2013 at 11:57

1 Answer 1

3

Because x is not dependent, it will be looked up in the context where the template is defined. In that context, the compiler knows nothing of T, and cannot look in dependent base classes. How can it, for example, know anything of A<T> without knowing what T is. (There could be a specialization of A for example, with completely different members.)

Sign up to request clarification or add additional context in comments.

8 Comments

This doesn't explain why the compiler cannot see x. The base class isn't T, it's A<T>, and the definition of A<T> is already available when B1 is defined. I know the language doesn't work that way, but the question, as I read it, is "why doesn't it?"
Actually, I think the question here is more about why it can't see x given that we know the base type is A<int>. No template arguments here at all.
The base class is dependent on T. The compiler cannot see it until it knows what T is. (What if A<T> is explicitly specialized for some types, for example?)
@sftrabbit When we know that the base class is A<int>, it can see x, and there is no problem. When all that is known is that it is A<T>, then the compiler cannot know what A<T> contains until it knows what T is.
@pascal When you specialize A<int>, you can do pretty much whatever you want. If you want an example, look in the standard: std::allocator<void> has less than half the members of the generic std::allocator<T>.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.