Cygon
Cygon

Reputation: 9620

Can I Deduce the Return Type of a Function Passed as a Template Agument?

I have a templated method which accepts a function which is allowed to have any return type so long as it's an std::shared_ptr for a class inheriting from TService:

template<typename TService> struct BindSyntax {

  typedef std::shared_ptr<TService>(*CreateServiceFunction)(int);
  CreateServiceFunction myFunction;

  template<
    typename TResult,
    std::shared_ptr<TResult>(*TMethod)(const ServiceProvider &)
  >
  void ToFactoryMethod() {
    static_assert(
      std::is_base_of<TService, TResult>::value, "Result must inherit service"
    );

    myFunction = [](int mooh) {
      return std::static_pointer_cast<TService>(TMethod(mooh));
    };
  }
};

When calling the ToFactoryMethod<>() method, I always have to specify the return type of the function I provide it with:

BindSyntax<Base> bind;
bind.ToFactoryMethod<Derived, exampleFactory>();

-

Can I get the ToFactoryMethod<>() method to somehow deduce the return type of the passed function?

I'd like to write just

BindSyntax<Base> bind;
bind.ToFactoryMethod<exampleFactory>();

Runnable code snippet here: https://ideone.com/FYtN6Q

Upvotes: 3

Views: 82

Answers (2)

4xy
4xy

Reputation: 3672

I suppose you can a bit rewrite the ToFactoryMethod to look like that

template<typename TResult>
void ToFactoryMethod(std::shared_ptr<TResult> (*TMethod)(const ServiceProvider&)) {
    static_assert(
            std::is_base_of<TService, TResult>::value, "Result must inherit service"
    );

    myFunction = [](int mooh) {
        return std::static_pointer_cast<TService>(TMethod(mooh));
    };
}

And then call it like that

bind.ToFactoryMethod(exampleFactory);

Upvotes: 2

Ben
Ben

Reputation: 1634

Can't you use decltype or std::result_of' to retrieve the return type of TMethod and use that in is_base_of?

Upvotes: 0

Related Questions