Issue
Is it possible for a class to monitor when its member function is called and the arguments provided to the function, without modifying the member functions? I have a class defined and I want to have the option to toggle such functionality without modifying the functions themselves. At the end of the objects lifetime I would like to output this information to a log file somewhere.
Solution
If you cannot change the original class you can instead write an adapter which does the logging for you.
Example:
#include <iostream>
#include <map>
class ProfilingSummary
{
public:
static ProfilingSummary& Instance()
{
static ProfilingSummary myInstance;
return myInstance;
}
void Log(const std::string& method)
{
auto result_pair = Results.insert(std::make_pair(method, 1));
if(!result_pair.second)
{
// method already inserted
auto& count = result_pair.first->second;
count++;
}
}
ProfilingSummary(ProfilingSummary const&) = delete; // Copy construct
ProfilingSummary(ProfilingSummary&&) = delete; // Move construct
ProfilingSummary& operator=(ProfilingSummary const&) = delete; // Copy assign
ProfilingSummary& operator=(ProfilingSummary&&) = delete; // Move assign
private:
ProfilingSummary() = default;
~ProfilingSummary()
{
std::cout << std::endl;
std::cout << "Profiling Summary: " << std::endl;
for(const auto& result : Results)
{
const auto method = result.first;
const auto count = result.second;
std::cout << method <<
" called " << count << std::endl;
}
}
std::map<std::string, int> Results;
};
struct Original
{
void Foo() { std::cout << "Hello World" << std::endl; }
};
struct OriginalAdapter
{
void Foo()
{
ProfilingSummary::Instance().Log(__FUNCTION__); // use symbol for function name, you can copy this for each method
_Original.Foo();
}
private:
Original _Original;
};
int main()
{
OriginalAdapter original;
original.Foo();
}
Output:
Hello World
Profiling Summary:
Foo called 1
Answered By - RoQuOTriX