在 boost::mpl::for_each() 中调用通用 lambda
Calling a generic lambda in boost::mpl::for_each()
这里有一些答案(如何遍历boost::mpl::list?是我开始的那个)意味着我应该能够构造一个通用的lambda来提供给boost::mpl::for_each(),但我找不到一个工作的例子,或者自己构建一个。
理想上,我希望能够在 lambda 中做的是采用这样的函数
template<typename T>
void TestFunction(const int &p)
{
T t(p);
std::cout << "p = " << p << ", t = " << t << std::endl;
};
我目前正在循环调用类似的东西
for(int k = 0; k < 2; ++k)
{
TestFunction<int>(k);
TestFunction<long>(k);
TestFunction<float>(k);
TestFunction<double>(k);
};
并将其替换为类似
typedef boost::mpl::list<int, long, float, double> ValidTypes;
for(int k = 0; k < 2; ++k)
{
// lambda definition that captures k
// boost::mpl::for_each(ValidTypes, ...) that calls the lambda.
};
这可能吗?如果不使用 for_each() 和其他 mpl 结构之一?我有一个运行的代码版本,我重载了 operator(),但如果可能的话,我希望看到一个 lambda 解决方案。
谢谢 安 迪。
如果您可以使用 C++14 的广义 lambda,则可以捕获 p
的值,并推断传递给 lambda 的当前有效类型的类型:
#include <boost/mpl/for_each.hpp>
#include <boost/mpl/list.hpp>
#include <iostream>
int main()
{
using ValidTypes = boost::mpl::list<int, long, float, double>;
for (auto k = 0; k < 2; ++k) {
boost::mpl::for_each<ValidTypes>([p = k](auto arg) {
using T = decltype(arg);
T t(p);
std::cout << "p = " << p << ", t = " << t << 'n';
});
}
}
活生生的例子。
编辑:为了获得额外的信用,这里有一个稍微高级的版本,也适用于非默认的可构造类型:
#include <boost/mpl/for_each.hpp>
#include <boost/mpl/list.hpp>
#include <iostream>
class NonDefaultConstructible
{
int value;
public:
NonDefaultConstructible(int const& p) : value(p) {}
friend auto& operator<<(std::ostream& ostr, NonDefaultConstructible const& ndc)
{
return ostr << ndc.value;
}
};
int main()
{
using ValidTypes = boost::mpl::list<int, long, float, double, NonDefaultConstructible>;
for (auto k = 0; k < 2; ++k) {
boost::mpl::for_each<ValidTypes, boost::mpl::make_identity<boost::mpl::_1>>([p = k](auto arg) {
using T = typename decltype(arg)::type;
T t(p);
std::cout << "p = " << p << ", t = " << t << 'n';
});
}
}
活生生的例子。
有关make_identity
使用有点复杂的解释,请参阅我的第一个问答!
相关文章:
- 我可以将调用类的"this"传递给 lambda 函数吗?
- 如何调用存储在指向"std::函数"的指针中的 lambda?
- 从具有按值捕获的 lambda 移动构造 std::函数时,移动构造函数调用两次
- 模拟成员函数调用 lambda
- 使用多个输入向量中值的笛卡尔乘积调用 lambda
- QT C++如何调用lambda one
- QTimer::singleShot 仅在间隔为 0 时调用 lambda
- 在结构中调用 lambda 函数
- 调用 lambda 的结构/类成员时程序崩溃并"bad_function_call"
- 如何调用lambda模板
- C++不能从映射调用 lambda 表达式
- C++函数调用 lambda obj,按值调用比按引用调用快
- 为什么 std::apply 可以调用 lambda 而不是等效的模板函数?
- 在类方法内调用lambda函数中的类方法
- variadic模板函数会以相反的顺序调用lambda参数
- 如何从另一个lambda函数调用lambda函数
- 当另一个调用 lambda 使用默认捕获时,lambda 的闭包可能会被破坏吗?
- 调用 lambda 时出现分段错误,从 C++11 中的高阶函数返回
- 在GDB中调用lambda函数
- 变量在调用lambda之前被销毁