我有模板类和一些使用它的策略。它只是执行具有特定策略的lambda。
template<template<class>class Policy, typename ReturnType>
class execute :Policy<ReturnType>
{
public:
ReturnType res;
execute(ReturnType(*func)())
{res = Policy<ReturnType>().launch(func);}
};
template<typename ReturnType>
struct Policy1 {
ReturnType launch(ReturnType(*func)())
{/*some code*/
return func();}
};
template<typename ReturnType>
struct Policy2 {
ReturnType launch(ReturnType(*func)())
{/*some code*/
return func();}
};
int main()
{
auto lambda_int = [] {return int(1); };
auto lambda_float = [] {return float(1.0); };
execute<Policy1, decltype(lambda_int())> exec1(lambda_int);
execute<Policy2, decltype(lambda_float())> exec2(lambda_float);
}
客户端代码完全可以满足我的需求。但是我两次指向lambda,我想将客户端代码中的类变量声明减少为:
execute<Policy1> exec3(lambda_float);
据我了解,我不能使用类似的东西,tempalte<auto ReturnType>
因为它仅适用于单个参数。我也不能使用默认参数,因为我想传递任何类型的lambda返回。
template<template<class>class Policy, typename ReturnType=int>
class execute :Policy<ReturnType>
问题是如何将函数返回类型(即构造函数args)传递给类模板参数?还是可能有另一种方式?
我不知道您的示例代码与实际代码有多少差异,但是如果我以它的面值来考虑,我将对其进行重组。
我首先看到的是,您Policy
不必是模板类。它没有任何需要类级模板的成员。相反,该launch
函数可以成为模板:
struct Policy {
template <class Callable>
auto launch(Callable&& callable) {
/*some code*/
return callable();
}
};
现在,您没有理由execute
要继承Policy
(对于策略类型设计这也是惯用的)。
我们仍然无法解决您的lambda类型扣除问题。理想情况下,我们将使用类模板参数推导,并且可以!考虑到上述所有内容,以下是我将如何更改您的内容execute
:
template<class Policy, class Callable>
struct execute {
using ResultType = std::invoke_result_t<Callable>;
execute(Policy&&, Callable&& callable)
{
res = Policy().launch(std::forward<Callable>(callable));
}
ResultType res;
};
您将可以像这样使用它:
void foo()
{
execute exec{Policy{}, [](){ return 10; }};
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句