我有一个模板化方法,它接受一个函数,只要它是 std::shared_ptr
就可以有任何返回类型。对于继承自 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));
};
}
};
调用 ToFactoryMethod<>()
时方法,我总是必须指定我提供给它的函数的返回类型:
BindSyntax<Base> bind;
bind.ToFactoryMethod<Derived, exampleFactory>();
-
我能得到 ToFactoryMethod<>()
吗?以某种方式推断所传递函数的返回类型的方法?
我只想写
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);
关于c++ - 我可以推断作为模板参数传递的函数的返回类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58564984/