Hey everyone,
I would like to hear your thoughts on an idea I've been toiling away over. Playing around with some code I was curious if I could try to create a small library filled with a few classes and override the default function behaviour of those classes. This was for test purposes so I could have a similar sort of design where I work if it was useful. Through experimenting I got something like this which is honestly not ideal:
#define TEST TestOverride::getInstance()
class TestOverride
{
public:
TestOverride() : winProcess([this](){ std::cout << "Standard winProcess: " << m_iWin << '\n'; })
{
}
~TestOverride() {}
static TestOverride& getInstance()
{
static TestOverride instance;
return instance;
}
template <typename T>
void OverrideWinProcess(T _Func)
{
winProcess = _Func;
}
void ProcessWins() const
{
winProcess();
}
int& getWin() { return m_iWin; }
int& getWinPos() { return m_iWinPos; }
bool& getFinishedProcessing() { return m_bFinishedProcessing; }
private:
int m_iWin;
int m_iWinPos;
bool m_bFinishedProcessing;
std::function<void()> winProcess;
};
#define WINPROCESS(x) []() \
{ \
int& m_iWin = TEST.getWin(); int& m_iWinPos = TEST.getWinPos(); bool& bFinishedProcessing = TEST.getFinishedProcessing(); x \
}
int main()
{
TEST.ProcessWins();
TEST.OverrideWinProcess(
WINPROCESS(
m_iWin += 1;
std::cout << "Overloaded: " << m_iWin << '\n';
));
TEST.ProcessWins();
TEST.ProcessWins();
return 0;
}
What would be more ideal, is if I could create a new function without having to define and declare references to things within the class to make them available to the lambda. So a possible implementation may look something like this:
#define TEST TestOverride::getInstance()
class TestOverride
{
public:
TestOverride() : winProcess([this](){ std::cout << "Standard winProcess: " << m_iWin << '\n'; })
{
}
~TestOverride() {}
static TestOverride& getInstance()
{
static TestOverride instance;
return instance;
}
template <typename T>
void OverrideWinProcess(T _Func)
{
winProcess = _Func;
}
void ProcessWins() const
{
winProcess();
}
private:
int m_iWin
int m_iWinPos;
bool m_bFinishedProcessing;
std::function<void()> winProcess;
};
int main()
{
TEST.ProcessWins();
TEST.OverrideWinProcess(
TEST <- [](){
m_iWin += 1;
std::cout << "Overloaded: " << m_iWin << '\n';
});
TEST.ProcessWins();
TEST.ProcessWins();
}
Where the lambda infers variable and function calls from whatever you point to. I thought about having something helpful like this to allow developers who work outside the library to be able to modify the library to suit their needs if the default options do not cover what they need to do.
Please let me know your criticisms to this sort of idea.
Thanks,
Michael