When we pass an initializer list as a variable argument, we encounter an issue as it lacks a defined type. To resolve this problem, we must explicitly provide the type specifier.
A straightforward method is to create a class with an std::initializer_list
constructor and an overloaded operator<<
. We can then utilize this class to pass the initializer list as a variable argument, as demonstrated below:
template<typename T>
struct V
{
V(std::initializer_list<T> v): m_t(v){}
friend std::ostream& operator<<(std::ostream& os, const V& v)
{
std::cout << "{ ";
for(const auto i: v.m_t)
{
std::cout << i << " ";
}
std::cout << "}";
return os;
}
std::initializer_list<T> m_t;
};
func_( 1,2.5,'a', "Hello", V{10, 20, 30, 40 }); //works now
The provided working demo yields the expected output:
1
2.5
a
Hello
{ 10 20 30 40 }
This method offers customization options to meet specific requirements.