fork(2) download
  1. #include <string>
  2. #include <memory>
  3. #include <vector>
  4.  
  5. class PacketData{
  6. struct Context {
  7. virtual ~Context() = default;
  8. };
  9. template<typename T>
  10. struct Instance : Context {
  11. Instance(T&& t):data_{std::move(t)}{
  12.  
  13. }
  14. T data_;
  15. };
  16. std::unique_ptr<Context> self_;
  17. public:
  18. template<typename T>
  19. PacketData(T in):self_{new Instance<T>{std::move(in)}}{}
  20. //move is easy, copy is harder ;)
  21.  
  22. template<typename T>
  23. bool isA(){
  24. return dynamic_cast<Instance<T>*>(self_.get()) != nullptr;
  25. }
  26. template<typename T>
  27. T& asA(){
  28. if(!isA<T>()){
  29. throw std::runtime_error("bad cast or something");
  30. }
  31. return dynamic_cast<Instance<T>*>(self_.get())->data_;
  32. }
  33. };
  34.  
  35. using Packet = std::vector<PacketData>;
  36.  
  37. int main() {
  38. Packet packet;
  39. packet.push_back(4);
  40. packet.push_back(4.4f);
  41. packet.push_back(std::string{"test"});
  42. int i = packet[0].asA<int>();
  43. float f = packet[1].asA<float>();
  44. std::string s = packet[2].asA<std::string>();
  45. return 0;
  46. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
Standard output is empty