gpt4 book ai didi

c++ - 可变参数模板将参数打包到std::vector

转载 作者:行者123 更新时间:2023-12-01 14:34:03 25 4
gpt4 key购买 nike

我是模板的新手,我真的不理解为什么这不起作用。我希望 vector 将使用这些值构建。

main.cpp


template <typename ...T>
void int_printf(T ...args)
{
std::vector<T> vec = {args...};

for(auto& v:vec)
{
std::cout << v << std::endl;
}
}

int main()
{
int_printf(1,2,3,4);

return 0;
}

预期结果
1
2
3
4

msvc编译器的 错误(已翻译)

src/main.cpp(35): error C3520: 'T': the parameter pack must be expanded in this context
src/main.cpp(37): error C3536: '<begin>$L0': can't be used before initialization
src/main.cpp(37): error C3536: '<end>$L0': can't be used before initialization
src/main.cpp(37): error C2100: invalid redirection

最佳答案

另一种稍微复杂的方法是添加一个初始模板参数,指定vec的类型,如下所示:

#include <iostream>
#include <vector>

template <typename T, typename ... Args>
void int_printf(Args ... args)
{
std::vector<T> vec = {args...};

for (auto& v : vec)
{
std::cout << v << std::endl;
}
}

int main()
{
int_printf<int>(1,2,3,4);
return 0;
}

如果将不兼容类型的列表传递给 int_printf,这可能会给出更清晰的错误消息。

关于c++ - 可变参数模板将参数打包到std::vector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61487324/

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