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)...
vec
类型的初始模板参数,如下所示:T
在此上下文中不是模板参数,而是模板参数包,在您的示例中它将扩展为T=[int,int,int,int]
。 std::vector
希望将类型作为模板参数而不是模板参数包传递。您可以使用std::common_type
解决此问题:std::vector<T>
时,T
不是单个类型,而是一组类型。您不能将其用于向量,因为它需要元素的单一类型。