[英]boost transform iterator and c++11 lambda
我試圖通過向適配器提供c ++ 0x lambda來使用boost :: adapters :: transformed。
以下代碼無法編譯。 我正在使用g ++ 4.6.2和boost 1.48。
#include <iostream>
#include <vector>
#include <boost/range/adaptors.hpp>
#include <boost/range/algorithm.hpp>
using namespace std;
namespace br = boost::range;
namespace badpt = boost::adaptors;
int main()
{
vector<int> a = {0,3,1,};
vector<int> b = {100,200,300,400};
auto my_ftor = [&b](int r)->int{return b[r];};
cout<<*br::max_element(a|badpt::transformed(my_ftor))<<endl;
}
關於我在這里做錯了什么的想法?
這是眾所周知的問題。 看這里
不久,你應該使用這個宏
#define BOOST_RESULT_OF_USE_DECLTYPE
使用decltype
而不是boost::result_of
。
從這里引用
如果您的編譯器支持decltype,那么您可以通過定義宏BOOST_RESULT_OF_USE_DECLTYPE來啟用自動結果類型推導,如下例所示。
Lambdas不好玩,因為它們不是默認構造的,這對迭代器來說是必要的。 這是我用於lambdas的包裝器:
#define RETURNS(...) -> decltype(__VA_ARGS__) { return (__VA_ARGS__); }
template<class Fun>
struct function_object
{
boost::optional<Fun> f;
function_object()
{}
function_object(Fun f): f(f)
{}
function_object(const function_object & rhs) : f(rhs.f)
{}
// Assignment operator is just a copy construction, which does not provide
// the strong exception guarantee.
function_object& operator=(const function_object& rhs)
{
if (this != &rhs)
{
this->~function_object();
new (this) function_object(rhs);
}
return *this;
}
template<class F>
struct result
{};
template<class F, class T>
struct result<F(T)>
{
typedef decltype(std::declval<Fun>()(std::declval<T>())) type;
};
template<class T>
auto operator()(T && x) const RETURNS((*f)(std::forward<T>(x)))
template<class T>
auto operator()(T && x) RETURNS((*f)(std::forward<T>(x)))
};
template<class F>
function_object<F> make_function_object(F f)
{
return function_object<F>(f);
}
然后你可以這樣做:
int main()
{
vector<int> a = {0,3,1,};
vector<int> b = {100,200,300,400};
cout<<*br::max_element(a|badpt::transformed(make_function_object([&b](int r)->int{return b[r];};)))<<endl;
}
@ ForEver的答案( #define BOOST_RESULT_OF_USE_DECLTYPE
)對我不起作用。 而@Paul的回答太長了(而且太籠統)。 更具體的解決方案可以是:
#include <iostream>
#include <vector>
#include <boost/range/adaptors.hpp>
#include <boost/range/algorithm.hpp>
using namespace std;
namespace br = boost::range;
namespace badpt = boost::adaptors;
int main()
{
vector<int> a = {0,3,1,};
vector<int> b = {100,200,300,400};
struct{
vector<int>* bP; //pointer, just to imitate lambda syntax...
int operator()(int r) const{return (*bP)[r];} //was my_ftor = [&b](int r)->int{return b[r];};
} my_ftor{&b}; //...here
cout<<*br::max_element(a|badpt::transformed(my_ftor))<<endl;
}
(這是2016年,Boost 1.58,這仍然是破碎的。至少沒有捕獲的lambda應該滿足boost::transformed
的要求。)
如果lambda沒有捕獲(不是你的情況),代碼會更簡單一點,或者你可以使用:
...
int(*my_ftor)(int) = [](int r)->int{return ...;}; // function pointer default constructible and callable
cout<<*br::max_element(a|badpt::transformed(my_ftor))<<endl;
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.