2

I am playing around with a test class I created. Code linked below.

template<bool...rest_of_string>
class bitstring
{
public:
    void print_this_handler()
    {
        cout << " END";
    }
};

template<bool A, bool... rest_of_string>
class bitstring<A, rest_of_string...> : public bitstring<rest_of_string...>
{
public:
    static const bool value = A;

    bitstring(){}

    void print_this()
    {
        cout << "\nPrinting Bitstring with " << sizeof...(rest_of_string) << " bits: ";
        print_this_handler();
    }
protected:

    void print_this_handler()
    {
        cout << A;
        static_cast<bitstring<rest_of_string...> >(*this).print_this_handler();
    }
};

int main()
{
    bitstring<0,1,0,1,0,1,1,0> str;
    str.print_this();
}

I run into an error when I call print_this_handler() from inside print_this(). It says that print_this_handler() is protected in class bitstring. However, each class derives from bitstring, so why can I not access the next highest class up? When I change protected to public, everything works fine, but I am just curious why this is not working. Thank you.

Exact Error message copied below:

C:\Users\main.cpp|195|error: 'void bitstring<A, rest_of_string ...>::print_this_handler() [with bool A = true; bool ...rest_of_string = {false, true, false, true, true, false}]' is protected within this context|
Saswat Mishra
  • 185
  • 1
  • 11

1 Answers1

2

You are trying to call the base class print_this_handler so you just need to specify the base class and call it directly, trying to do it through a casted pointer is giving you this issue. If you think of it this way, when you cast the this pointer to the base class, it is as if you had created an instance of the base class and then tried to call a protected member function. You can't do that, but if you just add the disambiguation to specify the base class function there is no issue and you can call it directly. You can take a look at this SO question/answer for a little more clarification and explanation: https://stackoverflow.com/a/357380/416574

Change this line:

static_cast<bitstring<rest_of_string...> >(*this).print_this_handler();

To this:

bitstring<rest_of_string...>::print_this_handler();
pstrjds
  • 16,840
  • 6
  • 52
  • 61