c++ - 从可变参数模板中读取参数

标签 c++ c++11

我对如何使用可变参数模板从元组中读取每个参数感到有点困惑。

考虑这个函数:

template<class...A> int func(A...args){
int size = sizeof...(A);
.... }

我从主文件中调用它,例如:

func(1,10,100,1000);

现在,我不知道如何扩展 func 的主体,以便能够分别读取每个参数,例如,我可以将参数存储在数组中。

最佳答案

您必须为使用第一个 N(通常是一个)参数的函数提供覆盖。

void foo() {
   // end condition argument pack is empty
}

template <class First, class... Rest> 
void foo(First first, Rest... rest) {
    // Do something with first
    cout << first << endl; 

    foo(rest...); // Unpack the arguments for further treatment
}

当您解压缩可变参数时,它会找到下一个重载。

示例:

foo(42, true, 'a', "hello");
// Calls foo with First = int, and Rest = { bool, char, char* }
// foo(42, Rest = {true, 'a', "hello"}); // not the real syntax

然后下一层我们展开之前的Rest并得到:

foo(true, Rest = { 'a', "hello"}); // First = bool

依此类推,直到 Rest 不包含任何成员,在这种情况下解包它会调用 foo()(没有参数的重载)。


如果不同类型存储包

如果你想存储整个参数包,你可以使用 std::tuple

template <class... Pack>
void store_pack(Pack... p) {
    std::tuple<Pack...> store( p... );
    // do something with store
}

但是这似乎不太有用。

存储同质包装

如果包中的所有值都是同一类型,您可以像这样存储它们:

vector<int> reverse(int i) {
    vector<int> ret;
    ret.push_back(i);
    return ret;
}

template <class... R>
vector<int> reverse(int i, R... r) {
    vector<int> ret = reverse(r...);
    ret.push_back(i);
    return ret; 
}

int main() {
    auto v = reverse(1, 2, 3, 4);
    for_each(v.cbegin(), v.cend(), 
        [](int i ) { 
            std::cout << i << std::endl; 
        }
    );
}

然而,这似乎更少有用。

关于c++ - 从可变参数模板中读取参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3651499/

相关文章:

c++ - 如何在 C++ Sprintf 第二个(格式)参数中传递变量?

c++ - 软件电容

c++ - 如何在不知道大小的情况下读取文本文件并存储到数组中?

c++ - "no matching function for call to ‘async(std::launch, <unresolved overloaded function type>, std::string&)’“

C++ unordered_multimap 插入散列

c++ - 如何结合 C++ 字符串和 Arduino 字符串?

c++ - 简单的 GLUT 库问题

c++11异步段错误

c++ - 非虚拟单继承类层次结构中的基指针一致性

c++ - 为什么 `std::initializer_list`经常按值传递?