fork download
  1. #include <type_traits>
  2. #include <string>
  3. #include <iostream>
  4.  
  5. using namespace std;
  6.  
  7. void testString(string value) {
  8. cout << "A string: " << value << endl;
  9. }
  10.  
  11. void testInt(int value) {
  12. cout << "An int: " << value << endl;
  13. }
  14.  
  15. template <typename U>
  16. void testOther(U value) {
  17. cout << "Unknown type: " << value << endl;
  18. }
  19.  
  20. template <typename T>
  21. class Test {
  22. public:
  23.  
  24. constexpr Test(T value) : value(value) {}
  25.  
  26. void test() {
  27. if (is_same<T, string>::value) {
  28. string &_value = (*reinterpret_cast<string *>(&value));
  29. testString(_value);
  30. } else if (is_same<T, int>::value) {
  31. int &_value = (*reinterpret_cast<int *>(&value));
  32. testInt(_value);
  33. } else {
  34. testOther(value);
  35. }
  36. }
  37.  
  38. private:
  39.  
  40. T value;
  41. };
  42.  
  43. int main() {
  44. Test<string>("Hello, world!").test();
  45. Test<int>(42).test();
  46. Test<float>(42.1).test();
  47. }
Success #stdin #stdout 0s 3032KB
stdin
Standard input is empty
stdout
A string: Hello, world!
An int: 42
Unknown type: 42.1