C++ Logo

std-proposals

Advanced search

Re: Initialisers in ternary operators

From: Olaf van der Spek <ml_at_[hidden]>
Date: Fri, 11 Sep 2020 09:07:57 +0200
On Thu, Sep 10, 2020 at 11:06 PM Ronan Keryell via Std-Proposals
<std-proposals_at_[hidden]> wrote:

> On 9/10/20 1:36 PM, Dmitry Dmitry via Std-Proposals wrote:

> > Since C++17 we can have init-statements in if:
> > if (_*char buf[10]*;_ std::fgets(buf, 10, stdin)) { m[0] += buf; }
> >
> > That is excellent. But what about ternary operators (?:)?
> > It seems I cannot write something like this now:
> > return (_*auto It = Cont.find(42)*;_ It == Cont.end()) ? 0 : It->second;
> >
> > Is it deliberate?
> > Are there any objections?
> > What do you think?
>
> You can probably already have a similar outcome with:
>
> return [&] { auto It = Cont.find(42); return It == Cont.end() ? 0 :
> It->second; }();
>
> which is not that much longer.

Just write and use a find wrapper like these:
template <class T, class U>
const typename T::value_type::second_type& find_ptr2(const T& c, const U& v)
{
  static typename T::value_type::second_type z = typename
T::value_type::second_type();
  typename T::const_iterator i = c.find(v);
  return i == c.end() ? z : i->second;
}

template <class T, class U>
typename T::value_type::second_type& find_ptr2(T& c, const U& v)
{
  static typename T::value_type::second_type z = typename
T::value_type::second_type();
  typename T::iterator i = c.find(v);
  return i == c.end() ? z : i->second;
}


-- 
Olaf

Received on 2020-09-11 02:11:40