Is it a function for the index of the standard class?
-
There was an expectation of the 11 at the end of the program, but despite the fact that the compiler had failed the code without question, the program was interrupted by mistake.
#include "stdafx.h" #include <iostream> using namespace std; template <class ptrType> class A { public: ptrType ptrData; A<ptrType>::A(ptrType S) { ptrType ptrData = S; ptrData();//Вызов Foo по указателю из конструктора класса.(работает) } void Foo2(); }; template <class ptrType>void A<ptrType>::Foo2() { ptrData();//Вызов Foo по указателю.(не работает) } void Foo()//Интересующий функция. { cout << "1"; }; int main() { typedef void(*PTR_Foo)(); PTR_Foo ptrFoo = &(Foo);//Указатель на функцию Foo A<PTR_Foo> a(ptrFoo); a.Foo2();//Вызов Foo2 из экземпляра а класса А return 0; }
-
The problem with the line
ptrType ptrData = S;
You're misappropriating.
S
A local variable, not a field with the same name.Just write.
ptrData = S;
Or even better like that:
A<ptrType>::A(ptrType S) : ptrData(S) { ptrData(); }
Update (from discussion in commentaries):
To call a member ' s function instead of a free function
Foo
An index can be used for a member function:void (A<PTR_Foo>::*f)() = &A<PTR_Foo>::Foo2; (a.*f)();
At the same time, a copy of the type of object is required for the call.
A
♪You can also turn the index to a member function into a founctor (some kind of free function) with help.
std::function
♪ For a new classB
:class B { public: void Foo() { cout << "1"; }; };
received:
B b; std::function<void()> f2 = std::bind(&B::Foo, b); f2();
- and you can.
f2
to another class. But it's clear that you have a duty to guarantee that the objectb
to which the fuktor is attachedf2
will live at the time of the challenge.Well, or you can make a smart indication of him, so you don't take care of the time of life:
std::shared_ptr<B> pb = std::make_shared<B>(); std::function<void()> f2 = std::bind(&B::Foo, pb); f2();
P.S.: I think C++ is an overly complicated language.