Get a pointer to a class method with the keyword "using"

I am using Visual Studio 2010.

Why can't I get a pointer to a class method that has been "updated" to the public in the child class?

The following code does not compile:

#include <iostream> #include <functional> class Parent { protected: void foo() { std::cout << "Parent::foo()\n"; } }; class Child : public Parent { public: //void foo() { Parent::foo(); } //This compiles using Parent::foo; //This does NOT compile }; int main() { Child c; std::function < void () > f = std::bind(&Child::foo, &c); f(); return 0; } 

It gives an error:

 error C2248: 'Parent::foo' : cannot access protected member declared in class 'Parent' 
+4
source share
4 answers

It compiles here .

I think you just forgot to add the C ++ 11 parameter to your compiler.

For example, with gcc it -std=c++11 or -std=gnu++11 .

EDIT: It appears from here that the use of the alias declaration is not implemented in any version of Visual Studio.

In fact, here some people are talking about a compiler error .

The strange thing is here:

 c.foo(); // this works fine std::function < void () > f = std::bind(&Child::foo, &c); // this won't compile 
+3
source

For some reason, Visual Studio will not allow you to accept the address foo , although it is a public member of Child declared using the plain old C ++ 03 syntax.

 std::function<void()> f = std::bind(&Child::foo, &c); // won't compile auto fp = &Child::foo; // also won't compile 

Directly calling the function still works fine:

 c.foo(); // compiles OK 

Curiously, this means that you are using partial C ++ 11 VS2010 support to get around the flaw in your C ++ 03 support, using lambda to achieve the same effect as the bind expression:

 std::function<void()> f = [&c]{ c.foo(); }; // compiles OK! 
+1
source

This code is compiled using g++ 4.8.1 . Do you use C ++ 11? When I start, I get the following output:

 Parent::foo() 
0
source

In pre C ++ 11, this “use” allows you to not hide Parent :: foo in the following cases:

 class Parent { protected: void foo() {} }; class Child : public Parent { using Parent::foo; // without this, following code doesn't compile. public: // foo(int) hides Parent::foo without the 'using' void foo(int) { return foo(); } }; 
0
source

Source: https://habr.com/ru/post/1500344/


All Articles