【发布时间】:2015-06-17 14:40:01
【问题描述】:
以下代码无法为我编译:
#include <iostream>
#include <vector>
#include <boost/iterator/zip_iterator.hpp>
typedef boost::tuple<int&, float&> EntryTuple;
struct zip_func :
public std::unary_function<EntryTuple&, void>
{
void operator()(EntryTuple& t) const
{
std::cout << t.get<0>() << " " << t.get<1>() << std::endl;
}
};
int main()
{
const int N = 5;
std::vector<int> intVec(N,2);
std::vector<float> valueVec(N,5.5);
std::for_each(
boost::make_zip_iterator(
boost::make_tuple(intVec.begin(), valueVec.begin())
),
boost::make_zip_iterator(
boost::make_tuple(intVec.end(), valueVec.end())
),
zip_func()
);
return 0;
}
来自live example的错误消息:
在 /usr/include/c++/4.9/algorithm:62:0 包含的文件中, 来自 /usr/include/boost/utility/swap.hpp:24, 从 /usr/include/boost/tuple/detail/tuple_basic.hpp:40, 从 /usr/include/boost/tuple/tuple.hpp:33, 来自 /usr/include/boost/iterator/zip_iterator.hpp:19, 来自 prog.cpp:4: /usr/include/c++/4.9/bits/stl_algo.h: 在 '_Funct 的实例化中 std::for_each(_IIter, _IIter, _Funct) [with _IIter = boost::zip_iterator >, __gnu_cxx::__normal_iterator >, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type> >; _Funct = zip_func]': prog.cpp:34:1:
这里需要/usr/include/c++/4.9/bits/stl_algo.h:3755:14: 错误:不匹配调用 '(zip_func) (boost::iterator_facade >, __gnu_cxx::__normal_iterator >, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type> >, boost::tuples::cons >, boost::random_access_traversal_tag, boost::tuples::cons >, int>::reference)' __f(*__first); ^ prog.cpp:9:8: 注意:候选是:struct zip_func: ^ prog.cpp:12:8: 注意:void zip_func::operator()(EntryTuple&) const void operator()(EntryTuple& t) const ^ prog.cpp:12:8: 注意:参数 1 的未知转换来自 'boost::iterator_facade >, __gnu_cxx::__normal_iterator >, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type> >, boost::tuples::cons >, boost::random_access_traversal_tag, boost::tuples::cons >, int>::reference {aka boost::tuples::cons >}' 到 'EntryTuple& {aka boost::tuples::tuple&}'
如果我添加一些consts,它是compiles:
typedef boost::tuple<const int&, const float&> EntryTuple;
struct zip_func :
public std::unary_function<const EntryTuple&, void>
{
void operator()(const EntryTuple& t) const
{
std::cout << t.get<0>() << " " << t.get<1>() << std::endl;
}
};
是什么原因?
【问题讨论】:
-
Boost 的 zip 迭代器是仅查看的迭代器?顺便说一句,
std::unary_function是你们中的 C++03。