I've been trying to implement a multilevel inheritance using CRTP in C . But I'm facing the problem of accessing members with more than 2 levels. There is no problem with 2 levels, I'm using the friend and private constructor technique. The problem faces when I try to add another level to the hierarchy.
Here's my example:
template<typename CRTPType>
class State
{
private:
State() = default;
friend CRTPType;
protected:
float value = 0.0f;
}
template<typename CRTPType>
class AnimState : public State<AnimState<CRTPType>>
{
private:
State() = default;
friend CRTPType;
public:
void test() value = 5.0f; //Error, value undeclared
}
class IdleState : AnimState<IdleState>
{
public:
void test() value = 5.0f; //It works, obviously
}
I'm aware of the problem, the IdleState class will be friend of AnimState and State so it can access to both class memberers. But I also want the AnimState to be able to access to the State class members.
Any good solution out there?
Thanks in advance.
CodePudding user response:
In AnimState, value is inherited from a base that depends on a template parameter.
Because of that, it must be accessed using this->value, or AnimState::value, or State<...>::value.
That's probably because value could also be the name of a global variable, and may or may not exist in the parent depending on the value of the template parameter, so for your sanity, the compiler doesn't want to have to resort to switching between a global variable and an inhertied variable depending on the template argument. So it refuses to search for value in the base classes, unless you qualify it as suggested above.
