fork(1) download
  1. #include <memory>
  2. #include <type_traits>
  3.  
  4. // Fluent syntax helper to binds service implementations and factory methods
  5. template<typename TService> struct BindSyntax {
  6.  
  7. // Placeholder for real service factory function pointer registration.
  8. typedef std::shared_ptr<TService>(*CreateServiceFunction)(int);
  9. CreateServiceFunction myFunction;
  10.  
  11. // Define a factory method to provide the service
  12. // TODO: Can the compiler implicitly figure out the function's return type?
  13. template<typename TResult, std::shared_ptr<TResult>(*TMethod)(int)>
  14. void ToFactoryMethod() {
  15. static_assert(
  16. std::is_base_of<TService, TResult>::value, "Result must inherit service"
  17. );
  18.  
  19. myFunction = [](int mooh) {
  20. return std::static_pointer_cast<TService>(TMethod(mooh));
  21. };
  22. }
  23. };
  24.  
  25. // ------------------------------------------------------------------------- //
  26.  
  27. struct Base {};
  28. struct Derived : public Base {};
  29.  
  30. // Example factory method
  31. std::shared_ptr<Derived> exampleFactory(int) {
  32. return std::make_shared<Derived>();
  33. }
  34.  
  35. int main() {
  36. BindSyntax<Base> bind;
  37. bind.ToFactoryMethod<Derived, exampleFactory>();
  38.  
  39. // In the above call, I don't want to have to explicitly specify
  40. // 'Derived' as the return type of the method
  41. }
Success #stdin #stdout 0s 4368KB
stdin
Standard input is empty
stdout
Standard output is empty