fork download
  1. #include <iostream>
  2.  
  3. template<typename T>
  4. std::string getClassName()
  5. {
  6. std::string fullFuncName = __PRETTY_FUNCTION__;
  7. const char start[] = "with T = ";
  8. const char end[] = ";";
  9. auto beginning = fullFuncName.find(start);
  10. auto ending = fullFuncName.find(end, beginning);
  11. return {fullFuncName.begin() + beginning + sizeof(start) - 1,
  12. fullFuncName.begin() + ending};
  13. }
  14.  
  15. struct Test
  16. {
  17. Test()
  18. {
  19. std::cout << "Created instance of " << getClassName<std::decay_t<decltype(*this)>>() << '\n';
  20. }
  21. };
  22.  
  23. template<typename Derived>
  24. struct IPrintable
  25. {
  26. static std::string getMyName()
  27. {
  28. return getClassName<Derived>();
  29. }
  30. };
  31.  
  32. struct TestPrintable : IPrintable<TestPrintable>
  33. {
  34. void sayHello() const
  35. {
  36. std::cout << "Hi, I'm " << getMyName() << '\n';
  37. }
  38. };
  39.  
  40. int main() {
  41. std::cout << getClassName<int>() << '\n';
  42. Test test;
  43. TestPrintable testPrintable;
  44. testPrintable.sayHello();
  45.  
  46. return 0;
  47. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
int
Created instance of Test
Hi, I'm TestPrintable