std :: vector的可变参数模板打包参数>> [

问题描述 投票:1回答:3
我是模板的新手,我真的不理解为什么这不起作用。我期望向量将使用这些值来构造。

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
我是模板的新手,我真的不理解为什么这不起作用。我期望向量将使用这些值构建。 main.cpp模板

void int_printf(T ... args)...

c++ templates variadic-templates
3个回答
2
投票
另一种稍微复杂的方法是添加指定vec类型的初始模板参数,如下所示:

4
投票
您的代码中的问题是T在此上下文中不是模板参数,而是模板参数包,在您的示例中它将扩展为T=[int,int,int,int]std::vector希望将类型作为模板参数而不是模板参数包传递。您可以使用std::common_type解决此问题:

2
投票
std::vector<T>时,T不是单个类型,而是一组类型。您不能将其用于向量,因为它需要元素的单一类型。
© www.soinside.com 2019 - 2024. All rights reserved.