Reputation: 2017
I get the following error from the program below:
use of undeclared identifier 'value'
Why? And, how do I fix it using friend classes?
Thanks in advance.
template <typename T>
class F2 : public F1<T>
{
public:
F2(T o) : F1<T>(o) {}
void fun() {
std::cout << value << std::endl;
}
};
template <typename T>
class F1
{
public:
template <typename U>
friend class F2;
F1(T o) : value(o) {}
protected:
T value;
};
int main()
{
F2<int> f(3);
}
Upvotes: 0
Views: 139
Reputation: 28178
There are multiple problems here:
1) F2
isn't templated, so everywhere you're using T
in F2
is incorrect
2) F1
(the base class) is defined after F2
, move F2
to below F1
3) A base class is friending it's derived class. It shouldn't know about its derived class.
Is this your actual code? If so is the error you wrote your actual error? I would expect numerous errors for an array of reasons.
Upvotes: 0
Reputation: 55382
The C++ standard prescribes that all names that are not dependent on template parameters are bound when parsing a template function, rather than when it is instantiated, which is otherwise when the reference to the inherited value
could be detected.
The quick workaround is to use this->value
; because this
is dependent on the template parameter it is bound when the function is instantiated and the reference to the inherited value
is therefore permitted.
Upvotes: 2