14

Introducción.

En C++ no podemos crear contenedores de referencias:

std::vector<int&> vri;
In instantiation of ‘class __gnu_cxx::new_allocator<int&>’:
required from ‘class std::allocator<int&>’
required from ‘struct std::_Vector_base<int&, std::allocator<int&> >’
required from ‘class std::vector<int&>’
required from here
error: forming pointer to reference type ‘int&’
       typedef _Tp*       pointer;
                          ^~~~~~~

La implementación interna de los contenedores, requiere el uso de punteros al tipo contenido, lo que generaría el tipo prohibido puntero a referencia.

Por suerte, existe la plantilla std::reference_wrapper:

int x{1}, y{2}, z{3};
std::vector<std::reference_wrapper<int>> vr{x, y, z};
for (auto &v : vr)
    ++v;
std::cout << x << ' ' << y << ' ' << z << '\n';

El código anterior muestra 2 3 4.

Problema.

Estoy desarrollando una librería de filtros para contenedores de C++, por ejemplo el filtro where recibe un contenedor y devuelve std::reference_wrapper a los objetos del contenedor que cumplan el criterio:

template <typename container_t> auto range(const container_t &container)
{ return std::tuple{std::begin(container), std::end(container)}; };

template <typename container_t, typename predicate_t>
auto where(const container_t &container, predicate_t predicate)
{
    auto [b, e] = range(container);
    using type = std::remove_reference_t<decltype(*b)>;
    using reference = std::reference_wrapper<type>;

    std::vector<reference> result{};

    std::copy_if(b, e, std::back_inserter(result), predicate);

    return result;
}

Así, el siguiente código muestra 2 3 6 7:

int main()
{
    std::vector v{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

    for (auto &x : where(v, [](auto n){ return n & 0b10; }))
        std::cout << x << ' ';

    return 0;
}

El problema surge al concatenar filtros:

for (const auto &x :
    where(where(v, [](auto n){ return n & 0b10; }), [](auto n){ return n & 0b1; })) {
    std::cout << x << ' ';
}
no match for ‘operator<<’ (operand types are ‘std::ostream’ {aka ‘std::basic_ostream<char>’} and ‘const std::reference_wrapper<const std::reference_wrapper<const int> >’)
   std::cout << x << ' ';
   ~~~~~~~~~~^~~~

Dado que el primer where devuelve un std::vector<std::refernce_wrapper<int>>, el segundo trabajará sobre std::vector<std::refernce_wrapper<const std::refernce_wrapper<const int>>>.

Intento.

Para solucionar el problema, he creado una plantilla que si recibe un std::reference_wrapper<T>, desenvuelve el tipo T interno:

template <typename type_t>
struct unwrap
{
    using type = type_t;
};

template <typename type_t>
struct unwrap<std::reference_wrapper<type_t>>
{
    using type = type_t;
};

template <typename type_t>
using unwrap_t = typename unwrap<type_t>::type;

El desenvolvedor se desenvuelve1 bien:

int main()
{
    using ri = std::reference_wrapper<int>;
    using rf = std::reference_wrapper<float>;
    using rri = std::reference_wrapper<ri>;
    using rrri = std::reference_wrapper<rri>;

    std::cout
        << typeid(int).name() << '\t' << typeid(unwrap_t<int>).name() << '\n'
        << typeid(float).name() << '\t' << typeid(unwrap_t<float>).name() << '\n'
        << typeid(ri).name() << '\t' << typeid(unwrap_t<ri>).name() << '\n'
        << typeid(rf).name() << '\t' << typeid(unwrap_t<rf>).name() << '\n'
        << typeid(rri).name() << '\t' << typeid(unwrap_t<rri>).name() << '\n'
        << typeid(rrri).name() << '\t' << typeid(unwrap_t<rrri>).name();

    return 0;
}

Y muestra los datos esperados2:

  i   i
  f   f
  St17reference_wrapperIiE    i
  St17reference_wrapperIfE    f
  St17reference_wrapperIS_IiEE    St17reference_wrapperIiE
  St17reference_wrapperIS_IS_IiEEE    St17reference_wrapperIS_IiEE

Entero y flotante (int, float) quedan inalterados, envoltura de entero queda desenvuelta, y las envolturas anidadas se desenvuelven un nivel.

Pero no funciona dentro de where:

template <typename container_t, typename predicate_t>
auto where(const container_t &container, predicate_t predicate)
{
    auto [b, e] = range(container);
    using type = unwrap_t<std::remove_reference_t<decltype(*b)>>;
    //           ^^^^^^^^ <--- Desenvuelve el tipo del iterador.
    using reference = std::reference_wrapper<type>;

    std::vector<reference> result{};

    std::copy_if(b, e, std::back_inserter(result), predicate);

    // Chivatos sobre la función
    std::cout
        << __PRETTY_FUNCTION__ << "\n"
        << '\t' << "decltype(*b) = " << typeid(decltype(*b)).name() << '\n'
        << '\t' << "unwrap *b = " << typeid(unwrap_t<decltype(*b)>).name() << '\n'
        << '\t' << "type = " << typeid(type).name() << '\n'
        << '\t' << "reference = " << typeid(reference).name() << '\n'
        << '\t' << "unwrap type = " << typeid(unwrap_t<type>).name() << '\n';

    return result;
}


int main()
{
    std::vector v{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

    for (const auto &x :
        where(where(v, [](auto n){ return n & 0b10; }), [](auto n){ return n & 0b1; })) {
        std::cout << &x << ' ';
    }

    return 0;
}

Los chivatos dentro de where indican que el desenvolvedor funcionó en la primera llamada, mas no en la segunda:

  auto where(const container_t&, predicate_t) [with container_t = std::vector<int, std::allocator<int> >; predicate_t = main()::<lambda(auto:1)>]
      decltype(*b) = i
      unwrap *b = i
      type = i
      reference = St17reference_wrapperIKiE
      unwrap type = i
  auto where(const container_t&, predicate_t) [with container_t = std::vector<std::reference_wrapper<const int>, std::allocator<std::reference_wrapper<const int> > >; predicate_t = main()::<lambda(auto:2)>]
      decltype(*b) = St17reference_wrapperIKiE
      unwrap *b = St17reference_wrapperIKiE
      type = St17reference_wrapperIKiE
      reference = St17reference_wrapperIKS_IKiEE
      unwrap type = St17reference_wrapperIKiE

En la primera llamada, el contendedor de entrada es std::vector<int>, la des-referencia del iterador (decltype(*b)), la desenvoltura (unwrap_t<decltype(*b)>), el tipo (type) y la desenvoltura del tipo (unwrap_t<type>) son int, sólo es std::reference_wrapper el tipo reference.

En la llamada anidada, el contendedor de entrada es std::vector<std::reference_wrapper<const int>> y todos los tipos (salvo reference) son std::reference_wrapper<const int>, como si la desenvoltura no se estuviese aplicando.

Pregunta.

¿Qué está fallando en la plantilla para desenvolver envolturas? Sospecho que tiene algo que ver con la propagación de const.

Código disponible en Try it online!.


1Pun intended.

2Esos son los nombres que el compilador da a los tipos.

2
  • Has tratado de especializar aún más la plantilla unwrap para que al pasar un contenedor de reference_wrapper te devuelva el tipo del tipo? Me parece que vas a enfrentar el mismo problema al concatenar más de un nivel, donde tendrías un vector de rw a rw a rw...a T.
    – jestrada
    el 5 jun. 2020 a las 15:22
  • Estaba pensando que el comentario que tienes de la propagación de const--si es el problema--podría resolverse con referencias universales, que preservan si un objeto es o no const (me imagino si estás haciendo uso de vínculos/enlaces estructurados, auto return type, etc., estás familiarizado con perfect forwarding). Saludos.
    – jestrada
    el 5 jun. 2020 a las 15:30

1 respuesta 1

1

Usé el compilador de visual studio para ver que otra información sobre el tipado informaba. El resultado que mostró en consola fue:

        decltype(*b) = int
        underlying_type = int
        type = int
        reference = class std::reference_wrapper<int const >
        decltype(*b) = class std::reference_wrapper<int const >
        underlying_type = class std::reference_wrapper<int const >
        type = class std::reference_wrapper<int const >
        reference = class std::reference_wrapper<class std::reference_wrapper<int const > const >

Evidentemente hay algún problema con la resolución del unwrap_t tanto en visual studio como en gcc. La cuestión es que si reemplazamos

decltype(*b) 

por

typename container_t::value_type

el resultado en consola es:

        decltype(*b) = int
        underlying_type = int
        type = int
        reference = class std::reference_wrapper<int const >
        decltype(*b) = class std::reference_wrapper<int const >
        underlying_type = class std::reference_wrapper<int const >
        type = int
        reference = class std::reference_wrapper<int const >

Pero como el const se propaga el compilador da el siguiente error:

error: ambiguous overload for ‘operator=’ (operand types are ‘std::back_insert_iterator<std::vector<std::reference_wrapper<int>, std::allocator<std::reference_wrapper<int> > > >’ and ‘const int’)

Esto se soluciona si hacemos const al tipo contenido por el vector que estamos creando.

#include <iostream>
#include <vector>
#include <tuple>
#include <functional>
#include <algorithm>
#include <type_traits>

template <typename container_t> auto range(   container_t &container   ) { return std::tuple{std::begin(container), std::end(container)}; };
template <typename container_t> auto range(const container_t &container) { return std::tuple{std::begin(container), std::end(container)}; };

template <typename type_t>
struct unwrap
{
    using type = type_t;
};

template <typename type_t>
struct unwrap<std::reference_wrapper<type_t>>
{
    using type = type_t;
};

template <typename type_t>
using unwrap_t = typename unwrap<type_t>::type;

template <typename container_t, typename predicate_t>
auto where(const container_t &container, predicate_t predicate)
{
    auto [b, e] = range(container);
    using underlying_type = std::remove_const_t<typename container_t::value_type>;
    using type = unwrap_t<std::remove_reference_t<underlying_type>>;
    using reference = std::reference_wrapper<const type>;

    std::vector<reference> result{};

    std::copy_if(b, e, std::back_inserter(result), predicate);

    std::cout
        << __PRETTY_FUNCTION__ << "\n"
        << '\t' << "decltype(*b) = " << typeid(decltype(*b)).name() << '\n'
        << '\t' << "underlying_type = " << typeid(underlying_type).name() << '\n'
        << '\t' << "type = " << typeid(type).name() << '\n'
        << '\t' << "reference = " << typeid(reference).name() << '\n';

    return result;
}

int main()
{
    std::vector v{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

    for (const auto &x : where(where(v, [](auto n){ return n & 0b10; }), [](auto n){ return n & 0b10; }))
        std::cout << x << '\n';

    return 0;
}

Resultado en gcc:

auto where(const container_t&, predicate_t) [with container_t = std::vector<int, std::allocator<int> >; predicate_t = main()::<lambda(auto:1)>]
    decltype(*b) = i
    underlying_type = i
    type = i
    reference = St17reference_wrapperIKiE
auto where(const container_t&, predicate_t) [with container_t = std::vector<std::reference_wrapper<const int>, std::allocator<std::reference_wrapper<const int> > >; predicate_t = main()::<lambda(auto:2)>]
    decltype(*b) = St17reference_wrapperIKiE
    underlying_type = St17reference_wrapperIKiE
    type = i
    reference = St17reference_wrapperIKiE
2
3
6
7

Resultado en visual studio:

        decltype(*b) = int
        underlying_type = int
        type = int
        reference = class std::reference_wrapper<int const >
        decltype(*b) = class std::reference_wrapper<int const >
        underlying_type = class std::reference_wrapper<int const >
        type = int
        reference = class std::reference_wrapper<int const >
2
3
6
7
2
  • Gracias por aportar algo nuevo a esta olvidada pregunta. El problema es que el tipo contenido no tiene por qué ser const ¿Y si luego queremos operar sobre los datos filtrados? el 4 feb. 2021 a las 7:57
  • Para eso se debe quitar el const del parámetro container_t. Pero si haces eso no vas a poder anidar la función where.
    – Emiliano
    el 4 feb. 2021 a las 12:46

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.