gpt4 book ai didi

c++ - 为什么参数包扩展如此有限?

转载 作者:太空狗 更新时间:2023-10-29 21:20:33 25 4
gpt4 key购买 nike

我想知道,为什么 C++11 中的参数包扩展如此受限——是否只是 C++11 标准中的疏忽?为什么不能只执行 bar(args)...;?有没有比我做的更好的解决方法?

#include <iostream>

int bar(int i)
{
std::cout << i << ' ';
return 0;
}

template <typename T>
void boo(T t)
{
bar(t);
}

template <typename T, typename... Args>
void boo(T t, Args&&... args)
{
bar(t);
boo(args...);
}

template <typename... Args>
void dummy(Args&&... args)
{
}

template <typename... Args>
void foo(Args&&... args)
{
dummy(bar(args)...);

std::cout << std::endl;

int dummy1[sizeof...(Args)] = { (bar(args), 0)... };

std::cout << std::endl;

boo(args...);
}

int main()
{
foo(1, 3, 5);
}

最佳答案

The reference提到允许参数包扩展的不同上下文。因此,一种稍微更简洁的方法是

auto a = {bar(args)...};

如果 bar 的返回类型为 void,这将不起作用。

关于c++ - 为什么参数包扩展如此有限?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24316654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com