最小反射在C ++ [英] minimal reflection in C++

查看:154
本文介绍了最小反射在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.

我该如何做?

推荐答案

滚自己。通常你有一个字符串到对象创建函数的映射。

你需要类似下面的代码:

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.

这篇关于最小反射在C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆