26 Nisan 2022 Salı

std::empty

Giriş
std::enpty() aslında kendisine verilen container nesnesinin empty() metodunu çağırır. Metodun için şöyle
template <class C>
constexpr auto empty(const C& c) -> decltype(c.empty()); 
// (since c++17, until c++20)

template <class C>
[[nodiscard]] constexpr auto empty(const C& c) -> decltype(c.empty());
(since C++20) // (since c++20)

Öyleyse std::empty neden var ? Açıklaması şöyle
std::empty is useful for scenarios where a container may or may not provide a member function empty() for types providing a member function empty, std::empty provides a default implementation, but for a custom type not providing this function you can provide a function empty at namespace scope for use in templates; thanks to argument dependent lookup the function in the same namespace as the parameter will be used as fallback
Örnek
Şöyle yaparız
namespace Custom
{
  struct Container
  {
    bool m_empty;
  };

  constexpr bool empty(Container const& c) // custom implementation for our own type
  {
    return c.m_empty;
  }
}

template<class T>
void PrintEmpty(char const* containerName, T&& container)
{
  using namespace std;
  std::cout << containerName << " is " << (empty(container) ? "empty" : "not empty");
}

int main()
{
  PrintEmpty("std::vector<int>()", std::vector<int>());
  PrintEmpty("Container{}", Custom::Container{});
  PrintEmpty("Container{ true }", Custom::Container{ true });
}