boost-ext / di

C++14 Dependency Injection Library
https://boost-ext.github.io/di
1.13k stars 137 forks source link

lazy reference #504

Open sadaszewski opened 3 years ago

sadaszewski commented 3 years ago

Hi, thank you for the amazing library. It should make its way to boost officially, it is a strong and useful offering.

Expected Behavior

Maybe it could compile and work as the intuition suggests?

struct Foo {
  Foo(boost::di::extension::lazy<Bar&> bar): m_bar(bar) {}
  void later() {
    m_bar.get().baf();
  }
  boost::di::extension::lazy<Bar&> m_bar;  
};

Actual Behavior

It does not compile complaining that create<T&>() does not exist.

Specifications

Workaround

I was able to use the following lazy_reference class instead and then it works perfectly. Is it the only way?

template <class T>
class lazy_reference {
  template <class TInjector>
  static T& create(const void *injector) {

    return ((TInjector *)injector)->template create<T&>();
  }

 public:
  using boost_di_inject__ = inject<self<T&>>;

  template <class TInjector>
  explicit lazy_reference(const TInjector &i) noexcept : injector_((void *)&i), f(create<TInjector>) {}

  T& get() const { return (*f)(injector_); }

 private:
  const void *injector_ = nullptr;
  T& (*f)(const void *) = nullptr;
};

Thank you in advance for sharing your opinion. BR. -- S.