gbase
Loading...
Searching...
No Matches
gbase.h
Go to the documentation of this file.
1#pragma once
2
24// C++
25#include <iostream>
26#include <string>
27#include <typeinfo>
28
29// gbase
30#include "glogger.h"
31
32#if defined(__GNUG__)
33#include <cxxabi.h>
34#include <memory>
35
58std::string inline demangle(const char* name) {
59 int status = 0;
60 using deleter_t = void(*)(void*);
61 std::unique_ptr<char, deleter_t> demangled(abi::__cxa_demangle(name, nullptr, nullptr, &status), std::free);
62 return (status == 0 && demangled) ? demangled.get() : name;
63}
64
65#else
78std::string demangle(const char* name) {
79 return name; // No demangling on non-GNU compilers
80}
81#endif
82
83
114template <typename Derived>
115class GBase
116{
117public:
134 explicit GBase(const std::shared_ptr<GOptions>& gopt, std::string logger_name = "") {
135 log = std::make_shared<GLogger>(gopt, getDerivedName(), logger_name);
136 log->debug(CONSTRUCTOR, getDerivedName());
137 }
138
139 // sharing logger for heavy creations like gtouchable
156 explicit GBase(const std::shared_ptr<GLogger>& logger) : log(logger) {
157 }
158
170 virtual ~GBase() { if (log) log->debug(DESTRUCTOR, getDerivedName()); }
171
172 // Important: because we declared a destructor, default these explicitly.
184 GBase(const GBase&) = default; // shallow copy of shared_ptr
185
192 GBase& operator=(const GBase&) = default;
193
205 GBase(GBase&&) noexcept = default; // otherwise move would be suppressed
206
215 GBase& operator=(GBase&&) noexcept = default;
216
217private:
231 [[nodiscard]] std::string getDerivedName() const { return demangle(typeid(Derived).name()); }
232
233protected:
256 std::shared_ptr<GLogger> log;
257};
CRTP base class that provides logging facilities to the derived class.
Definition gbase.h:116
GBase(const std::shared_ptr< GOptions > &gopt, std::string logger_name="")
Construct a base that creates (and owns) a logger for the derived instance.
Definition gbase.h:134
GBase(const std::shared_ptr< GLogger > &logger)
Construct a base that reuses an existing logger.
Definition gbase.h:156
GBase & operator=(const GBase &)=default
Copy assignment (shallow copy of the logger pointer).
virtual ~GBase()
Destructor that logs object destruction when a logger is available.
Definition gbase.h:170
GBase(const GBase &)=default
Copy constructor (shallow copy of the logger pointer).
GBase(GBase &&) noexcept=default
Move constructor.
std::shared_ptr< GLogger > log
Shared logger used by the derived class for emitting messages.
Definition gbase.h:256
void debug(debug_type type, Args &&... args) const
std::string demangle(const char *name)
Fallback demangle implementation for non-GNU toolchains.
Definition gbase.h:78
CONSTRUCTOR
DESTRUCTOR