Notification texts go here Contact Us Buy Now!

How can I pass std::initializer_list in a variable number of arguments?

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.

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.