简体   繁体   English

在C ++中,可以使用一个函数来修改可变长度的元组吗?

[英]In C++, can you have a function that modifies a tuple of variable length?

In C++0x I would like to write a function like this: 在C ++ 0x中,我想编写如下函数:

template <typename... Types>
void fun(typename std::tuple<Types...> my_tuple) {
    //Put things into the tuple
}

I first tried to use a for loop on int i and then do: 我首先尝试在int i上使用for循环,然后执行以下操作:

get<i>(my_tuple);

And then store some value in the result. 然后在结果中存储一些值。 However, get only works on constexpr . 但是, get仅可在constexpr

If I could get the variables out of the tuple and pass them to a variadic templated function I could recurse through the arguments very easily, but I have no idea how to get the variables out of the tuple without get . 如果我可以从tuple获取变量并将其传递给可变参数的模板化函数,则可以很容易地遍历参数,但是我不知道如何在没有get的情况下从元组中get变量。 Any ideas on how to do that? 关于如何做到这一点的任何想法? Or does anyone have another way of modifying this tuple ? 还是有人有其他修改此tuple

Since the "i" in 由于“ i”在

get<i>(tup)

needs to be a compile-time constant, template instantiation is used to "iterate" (actually recurse) through the values. 需要是一个编译时常量,模板实例用于通过值“迭代”(实际上是递归)。 Boost tuples have the "length" and "element" meta-functions that can be helpful here -- I assume C++0x has these too. Boost元组具有“长度”和“元素”元功能,在这里可能会有所帮助-我认为C ++ 0x也具有这些功能。

Boost.Fusion is worth a look. Boost.Fusion值得一看。 It can 'iterate' over std::pair , boost::tuple , some other containers and its own tuple types, although I don't think it supports std::tuple yet. 它可以在std::pairboost::tuple ,其他一些容器及其自己的元组类型上“迭代”,尽管我认为它尚不支持std::tuple

Take a look at section 6.1.3.4 of TR1, http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1836.pdf 看看TR1的6.1.3.4节, http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1836.pdf

get is defined for both const and non-const qualified tuples and returns the appropriate reference type. 为const和非const限定元组都定义了get,并返回适当的引用类型。 If you change your function declaration to the following: 如果将函数声明更改为以下内容:

template 
void fun(typename std::tuple& my_tuple) {
    //Put things into the tuple
}

Then the argument to your function is a non-const tuple and get will allow you to make the necessary assignments once you've written the iteration using the information provided in previous responses. 然后,函数的参数是一个非常量元组,一旦使用先前响应中提供的信息编写了迭代,get便可以让您进行必要的赋值。

AFAICT, C++ tuples basically need to be handled with recursion; AFAICT,C ++元组基本上需要递归处理; there don't seem to be any real ways of packing/unpacking tuples except using the typesystem's only variadic template handling. 除了使用类型系统唯一的可变参数模板处理之外,似乎没有任何真正的打包/拆包元组的方法。

Have a look at my answer here for an example of template recursion to unwind tuple arguments to a function call. 请看一下我在这里的答案,以了解一个模板递归示例,以将元组参数展开为函数调用。

How do I expand a tuple into variadic template function's arguments? 如何将元组扩展为可变参数模板函数的参数?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM