How can I std::sqrt(boost::lambda::placeholder1_type)?



如何在boost::lambda::placeholder1_typestd::sqrt()

以下程序编译并执行正常。不知何故,它设法将boost::lambda::_1转换为双精度数并将其乘以 5.0。

#include <boost/lambda/lambda.hpp>
#include <iostream>
#include <cmath>
int main() {
std::array<double, 6> a = {1, 4, 9, 16, 25, 36};
std::for_each(a.begin(), a.end(),
std::cout << boost::lambda::_1 * 5.0 << " "
);
}

但是,如果我将std::cout行替换为

std::cout << std::sqrt(boost::lambda::_1) << " "

编译器 (G++) 说

参数 1 没有已知的转换 'boost::lambda::p laceholder1_type {aka const boost::lambda::lambda_functor>}' to "双">

那么,我如何从这个 std::for_each 循环中的boost::lambda::_1中获取平方根呢?

按照 C++11 的方式做:

#include <iostream>
#include <cmath>
#include <array>
#include <algorithm>
int main() {
std::array<double, 6> a = {1, 4, 9, 16, 25, 36};
std::for_each(a.begin(), a.end(),
[] (const auto&v ) { std::cout << sqrt(v) * 5.0 << " "; }
);
}

您需要延迟调用sqrt。为此,您应该使用 绑定表达式。

注意:您需要使用强制转换来选择正确的sqrt重载。

#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
#include <iostream>
#include <cmath>
int main()
{
std::array<double, 6> a = {1, 4, 9, 16, 25, 36};
std::for_each(a.begin(), a.end(),
std::cout << boost::lambda::bind(static_cast<double(*)(double)>(std::sqrt), boost::lambda::_1) << " "
);
}

输出:

1 2 3 4 5 6 

现场样品

啊,Boost.Lambda 的美好时光

int main() {
std::array<double, 6> a = {1, 4, 9, 16, 25, 36};
std::for_each(a.begin(), a.end(),
std::cout << boost::lambda::bind(static_cast<double(*)(double)>(std::sqrt), boost::lambda::_1 * 5.0) << " "
);
return 0;
}

最新更新