![](/img/trans.png)
[英]How can I use SFINAE to create a template function for containers, and deduce the return type based on an operator?
[英]Can I Deduce the Return Type of a Function Passed as a Template Agument?
我有一個模板化的方法,它接受一個 function ,只要它是從 TService 繼承的TService
的std::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);
您不能使用decltype
或std::result_of'
來檢索 TMethod 的返回類型並在TMethod
中使用它is_base_of
?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.