I am trying to use something like a strategy pattern, where there are two different Parsers Type1Parser and Type2Parser using an interface IParser.
There is another class ParsingText where we have 2 methods
setParser: which will set the parser type.getMethodreturn a method in the Parser. For eg.formatorparse.
#include <iostream>
#include<vector>
#include<string>
using namespace std;
class IParser
{
public:
virtual ~IParser() = default;
virtual string format() = 0;
virtual string parse() = 0;
};
class Type1Parser :public IParser
{
public:
string format() override
{
cout << " Formatting 1";
return string();
}
string parse() override
{
cout << " Parsering 1";
return string();
}
};
class Type2Parser :public IParser
{
public:
string format() override
{
cout << " Formatting 2";
return string();
}
string parse() override
{
cout << " Parsering 2";
return string();
}
};
typedef string(IParser::* parseFunc)();
class ParsingText
{
IParser* parser;
public:
void setParser(int p)
{
if (p == 1) parser = new Type1Parser();
if (p == 2) parser = new Type2Parser();
}
parseFunc getMethod(char o)
{
if (o == 'f') return parser->format;
else return parser->parse;
}
};
int main()
{
ParsingText* pt = new ParsingText();
pt->setParser(1);
parseFunc myMethod = pt->getMethod('f');
*myMethod();
return 0;
}
I am using a function pointer to return this class method. But I am not able to do so. I'm not sure what I'm doing wrong here?
In the
getMethodyou are trying to call the corresponding member function, rather than returning it. The correct syntax is as follows:This will resolve the compiler error. However, you have now next issue. In order to call the pointer to member function, you need a corresponding object instance as well, which is only privately available in
ParsingTextclass. One solution is to provide a getter forparserinstance, and invoke the pointer to member with that.See live demo in godbolt.org
That being said, this is not probably how you want to handle this case. The caller side could be much cleaner, if you had returned the wrapped version of the invoked member function with the correct
IParserinstance. Thestd::functioncomes in handy here.See live demo in godbolt.org