簡體   English   中英

可以推導出作為模板Agument傳遞的Function的返回類型嗎?

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

我有一個模板化的方法,它接受一個 function ,只要它是從 TService 繼承的TServicestd::shared_ptr ,就可以有任何返回類型:

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

在調用ToFactoryMethod<>()方法時,我總是必須指定 function 的返回類型,我提供給它:

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

-

我可以讓ToFactoryMethod<>()方法以某種方式推斷傳遞的 function 的返回類型嗎?

我只想寫

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

此處可運行代碼片段: https://ideone.com/FYtN6Q

我想你可以稍微重寫一下ToFactoryMethod看起來像這樣

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

然后這樣稱呼它

bind.ToFactoryMethod(exampleFactory);

您不能使用decltypestd::result_of'來檢索 TMethod 的返回類型並在TMethod中使用它is_base_of

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM