如何将模板 lambda 传递给函数并将其与不同类型一起使用
How to pass a template lambda to a function and use it with different types
我使用宏从旧的 C++ 时代继承了这段代码。我目前正在替换它,我正处于需要分解某些结构的地步。
通常,我有这个:
if(condition)
{
fun1(fun2(arguments, arg1)); // let's say arg1 is a vector of doubles
}
else
{
fun1(fun2(arguments, arg2)); // let's say arg2 is a double
}
好几次。 fun1()
有一组不同的参数,具体取决于 fun2()
参数类型,我也可以有 arg1
和 arg2
(真正的代码实际上有几层 if
s 每次都有一组不同的类型,每个分支内有几个额外的功能层)。
我想在一个可以接受模板 lambda 的函数中分解这个:
[&](auto arg) { fun1(fun2(arguments, arg));}
现在,问题是这是模板化的,所以我不能把它变成 std::function
,所以我不知道我应该使用什么样的参数来创建我的函数:
void dispatch(bool condition, const std::vector<double>& arg1, double arg2, ???? lambda)
{
if(condition)
{
lambda(arg1);
}
else
{
lambda(arg2);
}
}
C++17有这样的选项吗?甚至 C++20?
Now, the issue is that this is templated, so I can't turn it into a std::function
, so I don't know what kind of argument I should use to create my function
简单如下呢?
template <typename F>
void dispatch(bool condition, const std::vector<double>& arg1, double arg2, F lambda)
我的意思是...您可以看到 lambda 函数几乎是 class 和 operator()
对象的语法糖(模板 operator()
通用 lambda)。
所以你可以简单地通过class的模板类型拦截一个lambda。
如果 lambda
不可变,也许你可以接受它作为 const 引用 (F const & lambda
),以避免不必要的复制。
Is there such an option in C++17? or even C++20?
应该从 C++14 开始工作。
在 C++14 之前,泛型 lambda 不可用(但您可以将它们替换为带有模板 operator()
的显式 classes)。
我使用宏从旧的 C++ 时代继承了这段代码。我目前正在替换它,我正处于需要分解某些结构的地步。
通常,我有这个:
if(condition)
{
fun1(fun2(arguments, arg1)); // let's say arg1 is a vector of doubles
}
else
{
fun1(fun2(arguments, arg2)); // let's say arg2 is a double
}
好几次。 fun1()
有一组不同的参数,具体取决于 fun2()
参数类型,我也可以有 arg1
和 arg2
(真正的代码实际上有几层 if
s 每次都有一组不同的类型,每个分支内有几个额外的功能层)。
我想在一个可以接受模板 lambda 的函数中分解这个:
[&](auto arg) { fun1(fun2(arguments, arg));}
现在,问题是这是模板化的,所以我不能把它变成 std::function
,所以我不知道我应该使用什么样的参数来创建我的函数:
void dispatch(bool condition, const std::vector<double>& arg1, double arg2, ???? lambda)
{
if(condition)
{
lambda(arg1);
}
else
{
lambda(arg2);
}
}
C++17有这样的选项吗?甚至 C++20?
Now, the issue is that this is templated, so I can't turn it into a
std::function
, so I don't know what kind of argument I should use to create my function
简单如下呢?
template <typename F>
void dispatch(bool condition, const std::vector<double>& arg1, double arg2, F lambda)
我的意思是...您可以看到 lambda 函数几乎是 class 和 operator()
对象的语法糖(模板 operator()
通用 lambda)。
所以你可以简单地通过class的模板类型拦截一个lambda。
如果 lambda
不可变,也许你可以接受它作为 const 引用 (F const & lambda
),以避免不必要的复制。
Is there such an option in C++17? or even C++20?
应该从 C++14 开始工作。
在 C++14 之前,泛型 lambda 不可用(但您可以将它们替换为带有模板 operator()
的显式 classes)。