Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

minimal reflection in C++

I want to create a class factory and I would like to use reflection for that. I just need to create a object with given string and invoke only few known methods.

How i can do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You will have to roll your own. Usually you have a map of strings to object creation functions.
You will need something like the follwing:

class thing {...};
/*
class thing_A : public thing {...};
class thing_B : public thing {...};
class thing_C : public thing {...};
*/

std::shared_ptr<thing> create_thing_A(); 
std::shared_ptr<thing> create_thing_C(); 
std::shared_ptr<thing> create_thing_D();

namespace {
  typedef std::shared_ptr<thing> (*create_func)();

  typedef std::map<std::string,create_func> creation_map;
  typedef creation_map::value_type creation_map_entry;
  const creation_map_entry creation_map_entries[] = { {"A", create_thing_A}
                                                    , {"B", create_thing_B}
                                                    , {"C", create_thing_C} };
  const creation_map creation_funcs( 
          creation_map_entries, 
          creation_map_entries + sizeof(creation_map_entries)
                               / sizeof(creation_map_entries[0] );
}

std::shared_ptr<thing> create_thing(const std::string& type)
{
  const creation_ma::const_iterator it = creation_map.find(type);
  if( it == creation_map.end() ) {
     throw "Dooh!"; // or return NULL or whatever suits you
  }
  return it->second();
}

There are other ways to do this (like having a map of strings to objects from which to clone), but I think they all boil down to having a map of strings to something related to the specific types.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...