google/fruit

what should I do to use a string as an annotion of some bind?

fietiger opened this issue · 3 comments

if posibble I should use it like this:
Component getGreeterComponent() {
return fruit::createComponent().bind<Writer, StdoutWriter>("StdoutWriter");
}

Hi, no that's not allowed.
To avoid the xy problem, what are you trying to do?
If the set of strings that you'd use like this is fixed and known at compile time, you can define an empty struct for each as a marker and use that as annotation.

Thank you.
OK.I get it.I will find another way.

Here is my implement:

class Container {
public:
    Container() {

  }

  template <class impl,class _interface>
  void Reg(const std::string& name)
  {
      typedef Component<_interface> getGreeterComponent();
        getGreeterComponent* tmp = []() -> Component<_interface> {
        return fruit::createComponent().bind<_interface, impl>();
      };
      std::shared_ptr<Injector<_interface>> tmpx(new Injector<_interface>(tmp));
      _registration_types[std::type_index(typeid(_interface))][name] = tmpx;
  }
  template <class _interface>
  _interface* Resolve(const std::string& name) {
    std::shared_ptr<void> got = 
    _registration_types[std::type_index(typeid(_interface))][name];
    std::shared_ptr<Injector<_interface>> typex = std::reinterpret_pointer_cast<Injector<_interface>>(got);
    return typex->get<_interface*>();
  }

  public:
  typedef std::map<std::string, std::shared_ptr<void>> named_factory;
    typedef std::map<std::type_index, named_factory> registration_types;
    ;
    registration_types _registration_types;
    
};

and usage like this:

int main() {
  Container c;
  c.Reg<StdoutWriter, Writer>("Stdout");
  Writer* tmp2 = c.Resolve<Writer>("Stdout");
  tmp2->write("Hello world");


  return 0;
}