fork(1) download
  1. #include <iostream>
  2. #include <string>
  3.  
  4. using namespace std;
  5.  
  6. class Thing {
  7. public:
  8. virtual const char * type_name()=0;
  9. };
  10.  
  11. class OtherThing : public Thing {
  12. public:
  13. OtherThing() {}
  14. const char * type_name() { return "test"; }
  15. };
  16.  
  17. class ParameterThing : public Thing {
  18. std::string var;
  19. public:
  20. ParameterThing(const std::string var_) { var = var_; }
  21. const char * type_name() { return var.c_str(); }
  22. };
  23.  
  24. class NotAThing {
  25. public:
  26. };
  27.  
  28. template <typename TO_T, class ...Args>
  29. inline TO_T* turn_thing_to(Thing* p, Args&&... args)
  30. {
  31. static_assert(std::is_base_of<Thing, TO_T>::value, "TO_T is not derived from Thing");
  32. TO_T * newtype = new TO_T(args...);
  33. p = newtype;
  34. return newtype;
  35. }
  36.  
  37. int main() {
  38. Thing * thing = 0;
  39. thing = turn_thing_to<OtherThing>(thing);
  40. //compiler can't assign it to the pointer directory from the function argument, so
  41. //I returned it.
  42. std::cout << thing->type_name() << "\n";
  43. thing = turn_thing_to<ParameterThing>(thing, "test2");
  44. std::cout << thing->type_name();
  45.  
  46. /*
  47. thing = turn_thing_to<NotAThing>(thing); //gives compile error
  48. */
  49. return 0;
  50. }
Success #stdin #stdout 0s 3428KB
stdin
Standard input is empty
stdout
test
test2