mercredi 2 octobre 2019

How to mix auto with list initialization to return a std::pair properly?

I have this example which is a function that returns a std::pair which holds a string value and its size.

std::pair<std::string, int> getLastPair(const vector<string>& vec) {
    return{ vec.back(), vec.back().size() };
}

int main(){

    vector<string> names{ "An", "Apple", "A", "Day", "Keeps", "The", 
    "Doctor", "Away"};

    auto p{getLastPair(names)}; // ok p is a pair<string, int>
    std::cout << p.first << " " << p.second << std::endl;
    std::cout << typeid(p).name() << std::endl;

    auto p2 = { getLastPair(names) }; // why it is not a pair but an initializer list?
    std::cout << typeid(p2).name() << std::endl; // initializer list


    std::pair<std::string, int> p3 = { getLastPair(names) }; // ok a pair
    std::cout << p3.first << " : " << p3.second << std::endl;

}
  • Why the first initialization returns a pair as expected but the second one p2 is not a pair but an initializer_list instead?

Aucun commentaire:

Enregistrer un commentaire