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.getMethod
return a method in the Parser. For eg.format
orparse
.
#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?