Created
June 27, 2024 09:57
-
-
Save kadeng/9e9f78ced6dd64ec54292d7f873f92a9 to your computer and use it in GitHub Desktop.
Tracing type instantiation / declaration location
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <sstream> | |
#include <cmath> | |
#include <typeinfo> | |
#define TRACEABLE_DECLARATION static constexpr int __line__ = __LINE__; static constexpr const char *__file__ = __FILE__; | |
#ifdef __GNUG__ | |
#include <cxxabi.h> | |
#include <memory> | |
// Helper function to demangle type names | |
std::string demangle(const char* name) { | |
int status = -1; | |
std::unique_ptr<char[], void(*)(void*)> res{ | |
abi::__cxa_demangle(name, nullptr, nullptr, &status), | |
std::free | |
}; | |
return (status == 0) ? res.get() : name; | |
} | |
#else | |
std::string demangle(const char* name) { | |
return name; | |
} | |
#endif | |
template <typename T> std::string declaration_info() { | |
std::stringstream ss; | |
ss << demangle(typeid(T).name()) << " declared on line " << T::__line__ << " in file " << T::__file__; | |
return ss.str(); | |
} | |
// EXAMPLE USAGE | |
// Primary template definition | |
template <typename A,typename B> | |
class BinaryOps { | |
public: | |
TRACEABLE_DECLARATION; | |
static int ceil_multiply(A a, B b) { | |
return static_cast<int>(std::ceil(a) * std::ceil(b)); | |
} | |
}; | |
template <> | |
class BinaryOps<int,int> { | |
public: | |
TRACEABLE_DECLARATION; | |
static int ceil_multiply(int a, int b) { | |
return (a * b); | |
} | |
}; | |
template <typename OPS> | |
void try_ops() { | |
std::cout << "Ceil multiplication result: of 3.2 and 4.2 = " << OPS::ceil_multiply(3.3, 4.2) << " type used to perform ceil multiply: " << declaration_info<OPS>() << std::endl; | |
} | |
int main() { | |
try_ops<BinaryOps<int, int>>(); | |
try_ops<BinaryOps<float, float>>(); | |
try_ops<BinaryOps<float, int>>(); | |
return 0; | |
} | |
/* | |
Expected output: | |
Ceil multiplication result: of 3.2 and 4.2 = 12 type used to perform ceil multiply: BinaryOps<int, int> declared on line 50 in file /tmp/test.cpp | |
Ceil multiplication result: of 3.2 and 4.2 = 20 type used to perform ceil multiply: BinaryOps<float, float> declared on line 39 in file /tmp/test.cpp | |
Ceil multiplication result: of 3.2 and 4.2 = 16 type used to perform ceil multiply: BinaryOps<float, int> declared on line 39 in file /tmp/test.cpp | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment