|
| 1 | +// Copyright CERN and copyright holders of ALICE O2. This software is |
| 2 | +// distributed under the terms of the GNU General Public License v3 (GPL |
| 3 | +// Version 3), copied verbatim in the file "COPYING". |
| 4 | +// |
| 5 | +// See http://alice-o2.web.cern.ch/license for full licensing information. |
| 6 | +// |
| 7 | +// In applying this license CERN does not waive the privileges and immunities |
| 8 | +// granted to it by virtue of its status as an Intergovernmental Organization |
| 9 | +// or submit itself to any jurisdiction. |
| 10 | + |
| 11 | +#ifndef O2_TOBJECTWRAPPER_H |
| 12 | +#define O2_TOBJECTWRAPPER_H |
| 13 | +#include <TClass.h> |
| 14 | +#include <TObject.h> |
| 15 | +#include <cxxabi.h> |
| 16 | +#include <iostream> |
| 17 | +#include <memory> |
| 18 | +#include <stdexcept> |
| 19 | +#include <typeinfo> |
| 20 | + |
| 21 | +namespace o2 |
| 22 | +{ |
| 23 | +// anonymous namespace to prevent usage outside of this file |
| 24 | +namespace |
| 25 | +{ |
| 26 | +/// utility function to demangle cxx type names |
| 27 | +std::string demangle(const char* name) |
| 28 | +{ |
| 29 | + int status = -4; // some arbitrary value to eliminate the compiler warning |
| 30 | + std::unique_ptr<char, void (*)(void*)> res{ abi::__cxa_demangle(name, nullptr, nullptr, &status), std::free }; |
| 31 | + return (status == 0) ? res.get() : name; |
| 32 | +} |
| 33 | +} // end anonymous namespace |
| 34 | + |
| 35 | +/// A wrapper class to easily promote any type to a TObject |
| 36 | +/// does not take ownership of wrapped object and should not be used |
| 37 | +/// in tight loops since construction expensive |
| 38 | +template <typename T> |
| 39 | +class TObjectWrapper : public TObject |
| 40 | +{ |
| 41 | + public: |
| 42 | + TObjectWrapper(T* obj) : mObj(obj), TObject() |
| 43 | + { |
| 44 | + // make sure that a dictionary for this wrapper exists |
| 45 | + auto& t = typeid(*this); |
| 46 | + std::string message("Need dicionary for type "); |
| 47 | + auto typestring = demangle(t.name()); |
| 48 | + message.append(typestring); |
| 49 | + message.append("\n"); |
| 50 | + auto hasdict = TClass::HasDictionarySelection(typestring.c_str()); |
| 51 | + if (!hasdict) { |
| 52 | + throw std::runtime_error(message); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + TObjectWrapper() : TObjectWrapper(nullptr) {} |
| 57 | + void setObj(T* obj) { mObj = obj; } |
| 58 | + T* getObj() const { return mObj; } |
| 59 | + ~TObjectWrapper() override = default; |
| 60 | + |
| 61 | + private: |
| 62 | + T* mObj; |
| 63 | + ClassDefOverride(TObjectWrapper, 1); |
| 64 | +}; |
| 65 | +} |
| 66 | + |
| 67 | +#endif |
0 commit comments