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

ElG*_*ito 2 c++ templates variadic-templates

我是模板的新手,我真的不明白为什么这不起作用。我希望用这些值构造向量。

主程序


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;
}
Run Code Online (Sandbox Code Playgroud)

预期结果

1
2
3
4
Run Code Online (Sandbox Code Playgroud)

msvc 编译器出错(已翻译)

1
2
3
4
Run Code Online (Sandbox Code Playgroud)

Aza*_*ham 5

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

#include<type_traits>

template <typename ...T>
void int_printf(T ...args)
{
    //use std::common_type to deduce common type from template
    //   parameter pack
    std::vector<typename std::common_type<T...>::type> vec = {args...};

    for(auto& v:vec)
    {
        std::cout << v << std::endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

您应该注意,这仅在传递给int_printf具有公共类型的参数时才有效。