Search code examples
c++c++11initializer

Passing initializer as argument


Does initializer have a type? if so, what's? in this case, how could I make the following code work?

template <typename T>
int f(T a)
{
    return 0;
}

int main()
{
    f({1,2});
}

It give following error:

c.cpp:32:2: error: no matching function for call to 'f' f({1,2}); ^ c.cpp:18:5: note: candidate template ignored: couldn't infer template argument 'T' int f(T a) ^ 1 error generated.


Solution

  • When writing f({1,2}) you are using list initialization.

    If you want to pass the initializer list {1,2} to a function as is you can do it like this:

    #include <initializer_list>
    #include <iostream>
    
    template <typename T>
    int f(std::initializer_list<T> a) {
        for(const T& x : a) {
            std::cout << x << ", " << std::endl; // do something with the element
        }
        return 0;
    }
    
    int main() {
        f({1,2});
    }