Want more features on Pastebin? Sign Up, it's FREE!
Guest

Untitled

By: a guest on Sep 19th, 2012  |  syntax: C++  |  size: 2.18 KB  |  views: 23  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. #include<iostream>
  2. #include<string>
  3. #include<vector>
  4. #include "Regex.h"
  5.  
  6.  
  7. typedef std::string Name;
  8.  
  9. template <typename T>
  10. Name GetVectorTypeName() {
  11.   Name name = typeid(T).name();
  12.   Regex testvector("class std::vector<([^,]*)(?:[^]*)>");
  13.   std::vector<std::string> results;
  14.   if( testvector.Begins( name, results ) ) {
  15.     name = results[1];
  16.     Regex stripclassorstruct("(?:class|struct)\\s+([^]*)");
  17.     std::vector<std::string> name_matches;
  18.     if( stripclassorstruct.Find( name, name_matches )) {
  19.       name = name_matches[1];
  20.     }
  21.     for( std::string::iterator it = name.begin(), end = name.end(); it != end; ++it ) {
  22.       *it = tolower(*it);
  23.     }
  24.     return name;
  25.   } else {
  26.     return "";
  27.   }
  28. }
  29.  
  30.  
  31. typedef void (*CreatorFunc)(void**);
  32. typedef void (*ConstructorFunc)(void*, const std::vector<std::string>& data );
  33.  
  34. void CreateString( void **obj ) {
  35.   *obj = new std::string;
  36. }
  37. void DestroyString( void **obj ) {
  38.   std::string* str = (std::string*)*obj;
  39.   delete str;
  40.   *obj = NULL;
  41. }
  42. void ConstructString( void* obj, const std::string& data ) {
  43.   *(std::string*)obj = data;
  44. }
  45.  
  46. // Create instance
  47. template <typename T> void CreateVector( void **object ) {
  48.   *object = new T;
  49. }
  50.  
  51. // Vector specialised construction
  52. template <typename T> void ConstructVector( void* object, const std::vector<std::string>& data ) {
  53.   T* vec = (T*)object;
  54.   Name vector_type = GetVectorTypeName<T>();
  55.  
  56.   void *obj;
  57.   CreateString(&obj);
  58.   // All fields in this type should be valid objects for this vector
  59.   for( std::vector<std::string>::const_iterator it = data.begin(), end = data.end(); it != end; ++it ) {
  60.     // Push it
  61.     vec->push_back(*obj);
  62.     // Get address to new instance
  63.     void *newly = &vec->back();
  64.     ConstructString(newly,*it);
  65.   }
  66.   DestroyString(&obj);
  67.  
  68. }
  69.  
  70.  
  71. int main( int argc, char **argv ) {
  72.  
  73.   CreatorFunc vcreate = CreateVector<std::vector<std::string>>;
  74.   ConstructorFunc vcon = ConstructVector<std::vector<std::string>>;
  75.  
  76.   std::vector<std::string> data;
  77.   data.push_back("x");
  78.   data.push_back("y");
  79.   data.push_back("z");
  80.  
  81.   void *copy_obj;
  82.   vcreate(&copy_obj);
  83.   vcon(copy_obj,data);
  84.  
  85.   return 0;
  86. }
clone this paste RAW Paste Data