问题
in the code below, why does T2 give this error ‘m_t’ was not declared in this scope
, while TB is fine ?
And how can I have access to T1's members in T2 while still using templates ?
// All good
class TA
{
public:
TA() {}
protected:
int m_t;
};
class TB : public TA
{
public:
TB() {}
int get()
{ return m_t; }
protected:
};
// Error in T2
template<typename T>
class T1
{
public:
T1() {}
protected:
int m_t;
};
template<typename T>
class T2 : public T1<T>
{
public:
T2() {}
int get()
{ return m_t; }
protected:
};
回答1:
You need to use this->m_t
to make it a dependent name. When templates are compiled, names are looked up in two stages. Non-dependent names are looked up when the compiler first parses the template. Dependent names are looked up when the template is instantiated. Changing it to this->m_t
delays look-up until after the get
function is actually instantiated, in which case the base class type is known and the compiler can verify the member's existence.
来源:https://stackoverflow.com/questions/16420012/inheritance-of-class-members-mixed-with-templates