Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variadic template packed argument to std::vector

I'm new to templates and I don't really undestand why this doesn't work. I expected the vector to be constructed with those values.

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;
}

Expected result

1
2
3
4

Error by msvc compiler (translated)

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
like image 430
cdecompilador Avatar asked Jul 31 '26 23:07

cdecompilador


1 Answers

The issue in your code, is that T is not a template parameter in this context, it is a template parameter pack, which would expand to T=[int,int,int,int] in your example. std::vector expects a type to be passed as a template parameter, not a template parameter pack. You can solve this issue by using 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;
    }
}

You should note, this will only work if the arguments passed to int_printf have a common type.

like image 107
Azam Bham Avatar answered Aug 02 '26 15:08

Azam Bham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!