简体   繁体   中英

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

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM