Pergunta

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.

Foi útil?

Solução

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

Outras dicas

If you are wanting to execute your function for each value in the list, you can do this:

#include <iostream>

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

int main()
{
    for (int a : {1,2})
        std::cout << f(a) << std::endl;
}

Note this requires c++11 compatible compiler

If you want to pass the list to your function, then something like this:

#include <iostream>
#include <initializer_list>

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

int main()
{
    std::cout << f(std::initializer_list<int>{1, 2}) << std::endl;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top