【发布时间】:2015-03-24 02:03:59
【问题描述】:
给定boost::tuple 和std::tuple,如何在它们之间进行转换?
换句话说,你将如何实现以下两个功能?
template <typename... T> boost::tuple<T...> asBoostTuple( std::tuple<T...> stdTuple);
template <typename... T> std::tuple<T...> asStdTuple (boost::tuple<T...> boostTuple);
似乎是一个简单的事情,但我找不到任何好的解决方案。
我尝试了什么?
我最终通过模板编程解决了这个问题。它似乎适用于我的具体设置,但感觉不对(太冗长),我什至不确定它是否真的适用于所有情况(我稍后会谈到这一点)。
不管怎样,这里是有趣的部分:
template<int offset, typename... T>
struct CopyStdTupleHelper
{
static void copy(boost::tuple<T...> source, std::tuple<T...>& target) {
std::get<offset>(target) = std::move(boost::get<offset>(source));
CopyStdTupleHelper<offset - 1, T...>::copy(source, target);
}
static void copy(std::tuple<T...> source, boost::tuple<T...>& target) {
boost::get<offset>(target) = std::move(std::get<offset>(source));
CopyStdTupleHelper<offset - 1, T...>::copy(source, target);
}
};
template<typename... T>
struct CopyStdTupleHelper<-1, T...>
{
static void copy(boost::tuple<T...> source, std::tuple<T...>& target)
{ /* nothing to do (end of recursion) */ }
static void copy(std::tuple<T...> source, boost::tuple<T...>& target)
{ /* nothing to do (end of recursion) */ }
};
std::tuple<T...> asStdTuple(boost::tuple<T...> boostTuple) {
std::tuple<T...> result;
CopyStdTupleHelper<sizeof...(T) - 1, T...>::copy(std::move(boostTuple), result);
return result;
}
boost::tuple<T...> asBoostTuple(std::tuple<T...> stdTuple) {
boost::tuple<T...> result;
CopyStdTupleHelper<sizeof...(T) - 1, T...>::copy(std::move(stdTuple), result);
return result;
}
我想知道是否有更优雅的方式。使用boost::tuple 到std::tuple 包装现有API 似乎是一种非常常见的操作。
我试图为您提供一个最小的测试示例,其中仅缺少 asBoostTuple 和 asStdTuple 的实现。但是,对于我不完全理解的boost::tuples::null_type 的一些魔法,它无法编译。这也是我不确定我现有的解决方案是否可以普遍应用的原因。
这里是sn-p:
#include <tuple>
#include <boost/tuple/tuple.hpp>
template <typename... T>
boost::tuple<T...> asBoostTuple(std::tuple<T...> stdTuple) {
boost::tuple<T...> result;
// TODO: ...
return result;
}
template <typename... T>
std::tuple<T...> asStdTuple(boost::tuple<T...> boostTuple) {
std::tuple<T...> result;
// TODO: ...
return result;
}
int main() {
boost::tuple<std::string, int, char> x = asBoostTuple(std::make_tuple("A", 1, 'x'));
// ERROR:
std::tuple<std::string, int, char> y = asStdTuple<std::string, int, char>(x);
return x == y;
}
错误信息是:
example.cpp:20:38: error: no viable conversion from 'tuple<[3 *
...], 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>' to 'tuple<[3 * ...], (no
argument), (no argument), (no argument), (no argument),
(no argument), (no argument), (no argument)>'
...int, char> y = asStdTuple<std::string, int, char>(x);
我了解 Boost 的实现不是基于可变参数模板,这应该可以解释 null_type,但我仍然不确定如何避免该编译错误。
【问题讨论】:
标签: c++ boost tuples variadic-templates c++14