Skip to content

Latest commit

 

History

History
104 lines (90 loc) · 2.3 KB

if_constexpr.md

File metadata and controls

104 lines (90 loc) · 2.3 KB

Constexpr If

Actually, how would someone write a custom get<>() function for their class? (see Structured Bindings for why you might want to do that) Since each get<0>, get<1>, etc returns a different member, which are possibly different types... (oh no, template metaprogramming...)

C++14 C++17
class Foo {
  int myInt;
  string myString;
public:
  int const & refInt() const
  { return myInt; }
  string const & refString() const
  { return myString; }
};

namespace std
{
   template<> class tuple_size<Foo>
       : public integral_constant<int, 2>
   { };
   template<int N> class tuple_element<N, Foo>
   {
   public:
      using type =
      conditional_t<N==0,int const &,string const &>;
   };
}

template<int N> std::tuple_element_t<N,Foo>
get(Foo const &);

// here's some specializations (the real stuff)
template<> std::tuple_element_t<0,Foo>
get<0>(Foo const & foo)
{
  return foo.refInt();
}
template<> std::tuple_element_t<1,Foo>
get<1>(Foo const & foo)
{
  return foo.refString();
}
class Foo {
  int myInt;
  string myString;
public:
  int const & refInt() const
  { return myInt; }
  string const & refString() const
  { return myString; }
};

namespace std
{
   template<> class tuple_size<Foo>
       : public integral_constant<int, 2>
   { };
   template<int N> class tuple_element<N, Foo>
   {
   public:
      using type =
      conditional_t<N==0,int const &,string const &>;
   };
}


template<int N> auto & get(Foo const & foo)
{
  static_assert(0 <= N && N < 2, "Foo only has 2 members");

  if constexpr (N == 0)  // !! LOOK HERE !!
     return foo.refInt();
  else if constexpr (N == 1)    // !! LOOK HERE !!
     return foo.refString();
}

P.S. if constexpr (expression) doesn't check if the expression is constexpr. The expression must be constexpr (else it doesn't compile). The part that is constexpr is 'doing' the if. Don't think about this and what syntax might be better. The committee argued about it long enough.