Weird compiler error and template inheritance
Asked Answered
H

3

5

Could someone explain me why this code:

class safe_bool_base
{ //13
    protected:

        typedef void (safe_bool_base::*bool_type)() const;

        void this_type_does_not_support_comparisons() const {} //18

        safe_bool_base() {}
        safe_bool_base(const safe_bool_base&) {}
        safe_bool_base& operator=(const safe_bool_base&) { return *this; }
        ~safe_bool_base() {}
};

template <typename T=void> class safe_bool : public safe_bool_base
{
    public:

        operator bool_type() const
        {
            return (static_cast<const T*>(this))->boolean_test() ? &safe_bool_base::this_type_does_not_support_comparisons : 0;
        }

    protected:

        ~safe_bool() {}
};

template <> class safe_bool<void> : public safe_bool_base
{
    public:

        operator bool_type() const
        {
            return (boolean_test() == true) ? &safe_bool_base::this_type_does_not_support_comparisons : 0; //46
        }

    protected:

        virtual bool boolean_test() const = 0;
        virtual ~safe_bool() {}
};

Produces the following compiler error ?

c:\project\include\safe_bool.hpp(46) : error C2248: 'safe_bool_base::this_type_does_not_support_comparisons' : cannot access protected member declared in class 'safe_bool_base'
c:\project\include\safe_bool.hpp(18) : see declaration of 'safe_bool_base::this_type_does_not_support_comparisons'
c:\project\include\safe_bool.hpp(13) : see declaration of 'safe_bool_base'

Since both safe_bool templates derive from safe_bool_base, I don't understand why one can't access a protected member of the base class.

Am I missing something ?

Hawser answered 7/9, 2010 at 9:41 Comment(2)
This is a good question. Suggest you to add tag 'protected', 'base', 'derived' as well to the question for this to come up in searches/referencesRyon
@Chubsdad: Thanks. I can only add one more tag. (5 is the maximum tag count afaik.)Hawser
R
9

This should probably help (reproducible in a non template situation also)

struct A{
protected:
    void f(){}
};

struct B : A{
    void g(){&A::f;}        // error, due to Standard rule quoted below
};

int main(){
}

VS gives "'A::f' : cannot access protected member declared in class 'A'"

For the same code, Comeau gives

"ComeauTest.c", line 7: error: protected function "A::f" (declared at line 3) is not accessible through a "A" pointer or object void g(){&A::f;} ^

"ComeauTest.c", line 7: warning: expression has no effect void g(){&A::f;}

Here is the fixed code which achieves the desired intentions

struct A{
protected:
    void f(){}
};

struct B : A{
    void g(){&B::f;}        // works now
};

int main(){
}

So, why does the first code snippet not work?

This is because of the following rule in the C++ Standard03

11.5/1- "When a friend or a member function of a derived class references a protected nonstatic member function or protected nonstatic data member of a base class, an access check applies in addition to those described earlier in clause 11.102) Except when forming a pointer to member (5.3.1), the access must be through a pointer to, reference to, or object of the derived class itself (or any class derived from that class) (5.2.5). If the access is to form a pointer to member, the nested-name-specifier shall name the derived class (or any class derived from that class).

So change the return within operator functions as follows

return (boolean_test() == true) ? &safe_bool<void>::this_type_does_not_support_comparisons : 0; //46 

return (static_cast<const T*>(this))->boolean_test() ? &typename safe_bool<T>::this_type_does_not_support_comparisons : 0; 

EDIT 2: Please ignore my explanations. David is right. Here is what it boils down to.

struct A{
protected:
    int x;
};

struct B : A{
    void f();
};

struct C : B{};

struct D: A{            // not from 'C'
};

void B::f(){
    x = 2;         // it's own 'A' subobjects 'x'. Well-formed

    B b;
    b.x = 2;       // access through B, well-formed

    C c;
    c.x = 2;       // access in 'B' using 'C' which is derived from 'B', well-formed.

    D d;
    d.x = 2;       // ill-formed. 'B' and 'D' unrelated even though 'A' is a common base
}

int main(){} 
Ryon answered 7/9, 2010 at 10:7 Comment(11)
This sounds like the right answer! In idea what the rationale behind that rule is?Maletta
You should highlight "If the access is to form a pointer to member, the nested-name-specifier shall name the derived class", since this is a pointer-to-member.Spaceship
@Steve Jessop: Yup, made the bold formatting correctly. Thanks buddyRyon
@Oli Charlesworth: I guess they wanted derived classes to have access to only their own base classes protected members and not of others. So this basically ensures that obj1 of derived classes 'B' can modify the protected members of it's own base class 'A', and not of another obj2 of type 'B'. It is kind of something in between private and public.Ryon
@Chubsdad: I am not sure that I follow your example, the rational is correct in that allowing that would break the protected access qualifier, just not with other objects of the same type B but with other types. Consider struct A {...}; struct B : A {...}; struct C : A {...}; void B::break( X& x ) { x.*(&X::f)(); }. If X is B the code should compile and work, but if X is A, then the method could be called with an instance of C (unrelated to B) and it would call a non-public member from an unrelated class.Wallaby
... by forcing you to take the pointer at the most derived type it ensures that you cannot do that. C c; void B::break() { c.*(&B::f)(); } will produce a compile error as the member pointer is to B and not C.Wallaby
@David Rodríguez - dribeas : Yes, you are right. Have edited my post accordingly in EDIT 2.Ryon
@David Rodríguez - dribeas: +1s to both of your commentsRyon
@David Rodríguez - dribeas & @Chubsdad: Many thanks for you answers. I'm always astonished on how some people can quote the relevant parts of the standard that explains everything.Hawser
@ereOn: that's what having lots of eyes does for you. Everyone remembers or finds some bit of the standard that you wouldn't have done, you just need that person to see the question. Even better is if litb answers, he pretty much deals with everything on his own :-)Spaceship
That's it, either litb is present or you fall back to searching the standard. After doing it for a while you learn how to search for specific information, and then subtle things scape out... until litb comes around...Wallaby
M
1

I don't think this is anything to do with templates. Your example code can be reduced to this, and it still gives the equivalent error:

class A
{
    protected:
        typedef void (A::*type)() const;
        void foo() const {}
};


class B : public A
{
    public:
        operator type() const
        {
            return &A::foo;
        }
};

I believe the issue is you can't return member-function pointers to protected members in the public interface. (Edit: not true...)

Maletta answered 7/9, 2010 at 9:49 Comment(5)
Interesting. But if I remove the last template declaration, the compiler doesn't complain and there is still a method that returns the address of safe_bool_base::this_type_does_not_support_comparisonsHawser
Seems logical. By making a method protected you indicate that you only want to trust your 'neighbors' accessing your treasure chest. In this example, the neighbor simply gives anyone the key to the treasure chest (pointer to protected method)Excavate
@Patrick: I disagree. If this was true, it should apply to member variables as well. But as far as I know, nothing prevents me to return the address of a private or protected member variable in a public interface.Hawser
@Patrick: That's what I thought. But if you move operator bool_type() into the public interface of the base class, everything seems to compile ok.Maletta
@ereOn: regarding removing the last template definition; you no longer have an instantiation of the template, so there's no code to compile. If you instantiate the template another way (e.g. class safe_bool<int> v;), then you get the same error.Maletta
R
0

Chubsdad's answer clarifies your question of why there's an error for the template specialization.

Now the following C++ standard rule

14.7.2/11 The usual access checking rules do not apply to names used to specify explicit
instantiations
. [Note: In particular, the template arguments and names used in the function
declarator (including parameter types, return types and exception specifications) may be
private types or objects which would normally not be accessible and the template may be a
member template or member function which would not normally be accessible. — endnote]

would explain why the generic template instantiation wouldn't throw an error. It will not throw even if you have private access specifier.

Relations answered 7/9, 2010 at 11:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.