mercredi 23 mai 2018

How to use the auto keyword correctly while creating and passing initializer_list?

Following various advice on the Internet that since C++11 we should try to use auto everywhere, I ended up writing this code:

#include <iostream>
#include <vector>

template<typename T>
void print_size(std::vector<T> a)
{
    std::cout << a.size() << '\n';
}

int main()
{
    std::vector<int> v {1, 2, 3};
    print_size(v);

    auto w = {1, 2, 3};
    // print_size(w); // error: no matching function for call to 'print_size'
                      // candidate template ignored: could not match 'vector' against 'initializer_list'
}

This code compiles and runs without any issues. But if I enable to commented-out line, it produces the error mentioned in the comment.

I would like to know what is the correct way to write this code in C++11 and later versions.

Aucun commentaire:

Enregistrer un commentaire