etl icon indicating copy to clipboard operation
etl copied to clipboard

Feature request: add select1st and select2nd functors

Open evantill opened this issue 3 years ago • 4 comments

What do you think of adding select1st and select2nd functors in ETL library ?

(I can submit a PR)

evantill avatar Sep 16 '22 08:09 evantill

Sounds like a nice and simple addition. If you do a PR, don't forget to use the ETL_OR_STD::pair type.

jwellbelove avatar Sep 16 '22 08:09 jwellbelove

I have found two implementations :

  • Option A:
    template <class FirstType>
    struct select1st
    {
      typedef FirstType type;

      template <class T>
      inline const type& operator()(const T& x) const
      {
        return x.first;
      }

      template <class T>
      inline type& operator()(T& x)
      {
        return const_cast<type&>(x.first);
      }
    };

usage example :

typedef etl::pair<int, std::string> EtlPair;
EtlPair ep1(1, "Hello");

auto selector = select1st<EtlPair::first_type>();

CHECK_EQUAL(1, selector(ep1));
  • Option B:
    template<typename T>
    struct Select1st {
      typedef typename T::first_type type;

      inline type& operator()(T& x) const
      {
        return x.first;
      }

      inline const type& operator()(const T& x) const
      {
        return x.first;
      }
    };

usage example :

typedef etl::pair<int, std::string> EtlPair;
EtlPair ep1(1, "Hello");

auto selector = Select1st<EtlPair>();

CHECK_EQUAL(1, selector(ep1));

Which one to use in ETL ? And which naming convention to use ?

evantill avatar Sep 20 '22 08:09 evantill

I prefer option B. Option A looks odd as it seems to require type information that was already implied in the function name. BTW You don't need the inline for templates.

jwellbelove avatar Sep 20 '22 09:09 jwellbelove

Perfect (I also prefer option B).

evantill avatar Sep 20 '22 09:09 evantill

@jwellbelove can we close this issue ?

evantill avatar Oct 17 '22 07:10 evantill

To be included in next release.

jwellbelove avatar Oct 17 '22 08:10 jwellbelove