这个boost::元组代码可以转换为纯std::标准库代码吗?
is this boost::tuple code convertible to pure std:: standard library code?
以下boost代码可转换为纯c++11标准库吗?
我看到了std::tuple
和std::for_each
,但我似乎不能让他们互相玩。
我现在使用的是gcc 4.7.2。
#include <string>
#include <algorithm>
#include <iostream>
#include <boost/fusion/algorithm/iteration/for_each.hpp>
#include <boost/fusion/include/boost_tuple.hpp>
struct DoOutput
{
template<typename T>
void operator()(T const& t) const
{
std::cerr << t << std::endl;
}
void operator()(std::string const& t) const
{
std::cerr << "'" << t << "'" << std::endl;
}
};
int
main( int argc, char* argv[] )
{
boost::tuple< std::string, int > t = boost::make_tuple( "foo", 42 );
boost::fusion::for_each( t, DoOutput() );
return 0;
}
不可以,代码不能直接转换。
提振。Fusion是一个用于处理元组的库,因此它的for_each
适用于元组,即具有零或多个异构类型的结构。std::for_each
使用迭代器范围,它是同质类型值的范围。
使用类似index_tuple.h的东西,你可以把它改成这样:
struct sink {
template<typename... T>
sink(T&&...) { }
};
template<typename T, typename F>
int apply(T&& t, F& f)
{
f(std::forward<T>(t));
return 0;
}
template<typename Tuple, typename F, unsigned... Indices>
void apply(Tuple&& t, F&& f, index_tuple<Indices...>)
{
sink{ apply(std::get<Indices>(std::forward<Tuple>(t)), f)... };
}
int main()
{
std::tuple< std::string, int > t = std::make_tuple( "foo", 42 );
apply(t, DoOutput(), make_index_tuple<std::tuple_size<decltype(t)>::value>::type() );
}
创建一个类型index_tuple<0,1>
并调用apply
,它将参数包Indices
推导为{0, 1}
,然后将该包展开为:
sink{ apply(std::get<0>(t), f), apply(std::get<1>(t), f) };
其中f
是类型为DoOutput
的函数对象,并且每个应用程序调用f(tn)
初始化临时sink
只是因为你不能在表达式中展开参数包,例如,这是无效的:
f(std::get<Indices>(t))...;
因此,将包扩展为对象构造函数的初始化列表,这也保证了包扩展的每个元素都按顺序求值。
No。c++ 11标准库不包括boost::fusion
的功能。您所能期望的最好结果是使std::tuple
与boost::fusion
一起工作:
#include <string>
#include <algorithm>
#include <iostream>
#include <tuple>
#include <boost/fusion/algorithm/iteration/for_each.hpp>
#include <boost/fusion/adapted/std_tuple.hpp> //This feature is undocumented
struct DoOutput
{
template<typename T>
void operator()(T const& t) const
{
std::cerr << t << std::endl;
}
void operator()(std::string const& t) const
{
std::cerr << "'" << t << "'" << std::endl;
}
};
int
main( int argc, char* argv[] )
{
std::tuple< std::string, int > t = std::make_tuple( "foo", 42 );
boost::fusion::for_each( t, DoOutput() );
return 0;
}
相关文章:
- 在C++标准中做格式好意味着代码可以编译
- 标准对此指向成员函数类型模板参数有何说明?是我的代码有误,还是 MSVS 16.6 有问题?
- 如何知道用于实现标准代码段的确切数据结构和算法,例如在C++STL中?
- 如何在C++中执行命令并获取命令的返回代码标准输出和标准
- 如何在C++代码之上使用标准的Xcode GUI
- 为什么此代码从标准输入中少一个输入?
- 为什么我的 RLE 代码显示标准超出 C++ 的范围?
- 如何在C++代码中灵活使用和替换标准::shared_ptr或标准::unique_ptr或原始指针?
- C++标准提案代码:什么是 N 和 P?
- 此代码中的数组初始化样式是什么?这是标准的吗?
- 代码库找不到标准C++库标头
- 从 ASM 调用C++代码中标准库的链接
- 关于使用C 11标准编制C 98代码
- 哪个C 标准包括要添加到对象文件中的文件强制代码 /数据
- 有没有一种标准方法来确保一段代码在全局范围内执行
- 这段代码在我的电脑上编译,但不在竞赛服务器上的标准 C++98 编译器上编译
- 应根据C 标准进行以下代码编译
- 代码::块无法识别标准::线程
- 在C++代码中包含标准 C 标头在链接规范(外部"C"、外部"C++")中,指定的行为是什么?
- Eclipse的代码标准(而不是样式)强制执行器