If I enable line number 4 in below code then I end up in getting compilation error , while I am doing same thing (calling getFp1) outside the class and that works perfectly fine .
**Compilation Error** : In member function 'std::function<void(std::__cxx11::basic_string<char>)> testClass::getFp()':
Practice.cpp:23:14: error: cannot convert 'testClass::myTestFunction' from type 'void (testClass::)(std::string)' {aka 'void (testClass::)(std::__cxx11::basic_string<char>)'} to type 'std::function<void(std::__cxx11::basic_string<char>)>'
23 | return myTestFunction;
| ^~~~~~~~~~~~~~
Code
#include <iostream>
#include <functional>
#include <string>
//#define CLASS 1 -------------> Enabling this throws compilation error (?)
using namespace std;
void printMessage(string str){
cout << str << endl;
}
void testFunction(std::function<void(std::string)> fp,string s){
fp(s);
}
#ifdef CLASS
class testClass {
public :
void myTestFunction(std::string s){
cout << s << endl;
}
public :
std::function<void(std::string) > getFp(){
return myTestFunction;
}
};
#endif
std::function<void(std::string) > getFp1(){
return printMessage;
}
int main(){
std::function<void(string)> fp = printMessage;
fp("Whats up !!") ;
testFunction(fp,"All is Well");
#ifdef CLASS
testClass t ;
auto fp1 = t.getFp();
fp1("Calling Private Method ?");
#endif
auto fp2 = getFp1();
fp2("Great !!");
return 0;
}
============================