c++ - Boost.Tuple 与 C++0x 可变参数模板兼容吗?

标签 c++ gcc c++11 variadic boost-tuples

我在玩可变参数模板 (gcc 4.5) 时遇到了这个问题:

template <typename... Args>
boost::tuple<Args...>
my_make_tuple(Args... args)
{
   return boost::tuple<Args...>(args...);
}

int main (void)
{
    boost::tuple<int, char> t = my_make_tuple(8, 'c');
}

GCC 错误信息:

sorry, unimplemented: cannot expand 'Arg ...' into a fixed-length argument list
In function 'int my_make_tuple(Arg ...)'

如果我用 std::tuple 替换每次出现的 boost::tuple,它编译得很好。
boost元组实现有问题吗?或者这是一个 gcc 错误?

我现在必须坚持使用 Boost.Tuple。您知道任何解决方法吗?
谢谢。

最佳答案

它似乎不喜欢像 Boost 那样将 Args... 扩展到 T1, T2, T3, ..., T9

作为解决方法,使用不需要此扩展的结构:

#include <boost/tuple/tuple.hpp>

template <typename... Args>
auto my_make_tuple(Args... args) -> decltype(boost::make_tuple(args...))
{
   return {args...};
}

int main (void)
{
    boost::tuple<int, char> t = my_make_tuple(8, 'c');
}

另一种选择可能是手动进行扩展,因为 boost::tuple 最多支持 10 个参数。

#include <boost/tuple/tuple.hpp>

template <unsigned, class, class...> struct nth_argument;

template <unsigned N, class Default, class T, class... Args>
struct nth_argument<N, Default, T, Args...>
{
    typedef typename nth_argument<N - 1, Default, Args...>::type type;
};

template <class Default, class T, class... Args>
struct nth_argument<0, Default, T, Args...>
{
    typedef T type;
};

template <unsigned N, class Default>
struct nth_argument<N, Default>
{
    typedef Default type;
};

template <typename ...Args>
struct tuple_from_var_template
{
    typedef boost::tuple<
        typename nth_argument<0, boost::tuples::null_type, Args...>::type,
        typename nth_argument<1, boost::tuples::null_type, Args...>::type,
        typename nth_argument<2, boost::tuples::null_type, Args...>::type,
        typename nth_argument<3, boost::tuples::null_type, Args...>::type,
        typename nth_argument<4, boost::tuples::null_type, Args...>::type,
        typename nth_argument<5, boost::tuples::null_type, Args...>::type,
        typename nth_argument<6, boost::tuples::null_type, Args...>::type,
        typename nth_argument<7, boost::tuples::null_type, Args...>::type,
        typename nth_argument<8, boost::tuples::null_type, Args...>::type,
        typename nth_argument<9, boost::tuples::null_type, Args...>::type
    > type;
};

template <typename... Args>
typename tuple_from_var_template<Args...>::type my_make_tuple(Args... args)
{
   return typename tuple_from_var_template<Args...>::type(args...);
}

int main (void)
{
    boost::tuple<int, char> t = my_make_tuple(8, 'c');
}

关于c++ - Boost.Tuple 与 C++0x 可变参数模板兼容吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2709315/

相关文章:

C++虚拟继承和类型转换/复制构造函数混淆

c++ - Intel vs GCC on constexpr

我可以强制 gcc 检测所有未定义的行为吗?

c - C语言的基本封装

c++ - 变量的静态初始化失败

c++ - 我可以将 std::array 转换为切片吗?或者还有什么我可以用的吗?

c++ - std::vector 的高效初始化

c++ - 关于 CPP 文件和 header

objective-c - 使用 LLVM GCC 4.2 不会让我将 CFStringRef 桥接到 NSString

visual-studio - 如何搜索文件以查找整数