Sample code:
template<typename T, int X>
struct A {
T a = X;
};
template<int X>
struct B : public A<int, X> {
int fun() {
// return A<int, X>::a; // Method 1
// return this->a; // Method 2
return a; // Wrong!
}
};
struct C : public A<int, 564> {
int fun() {
return a; // Correct
}
};
int main() {
B<78> b;
C c;
std::cout << b.fun() << std::endl;
std::cout << c.fun() << std::endl;
return 0;
}
class B & C inherited from class A, which has a public member a
.
In class C, we can access a
directly, but we cann't do that in class B.
Compiler will raise an error:
error: 'a' was not declared in this scope
My questions are:
Why access
a
directly in class B is wrong and in class C is correct?I found two methods to access
a
in class B, see code snippet above. They both work, but not convenient. I wonder is there any better way to do it?