vendredi 18 août 2023

How to use universal reference in C++11

We would like to combine the following 2 map_at() functions into one, using universal reference T&&. Could somebody help?

template<typename T> // version const
const typename T::mapped_type& map_at(const T& m, const typename T::key_type& key)
{
    if (const auto& iter = m.find(key); iter != m.cend()) {
        return iter->second;
    }
    else {
        throw std::exception("blah");
    }
}

template<typename T> // version non-const
typename T::mapped_type& map_at(T& m, const typename T::key_type& key)
{
    if (const auto& iter = m.find(key); iter != m.cend()) {
        return iter->second;
    }
    else {
        throw std::exception("blah");
    }
}

int main()
{
    using T = std::map<int, float>;
    T t;
    const T ct;

    try {
        map_at(ct, 3); // calls version const
    }
    catch (...){}

    try {
        map_at(t, 3); // calls version non-const
    }
    catch (...){}
}

We tried the following with T&&, but get error

1> ConsoleApplication1.cpp(557,9): error C2672: 'map_at': no matching overloaded function found

template<typename T> // version T&&
typename T::mapped_type&& map_at(T&& m, const typename T::key_type& key)
{
    if (const auto& iter = m.find(key); iter != m.cend()) {
        return iter->second;
    }
    else {
        throw std::exception("blah");
    }
}

Aucun commentaire:

Enregistrer un commentaire