Overloading — enable_if (3)

// Copyright 2014 Andrzej Krzemienski.
//
// Inspired by Pawel Turkowski's solution.
//
// This shows how to use enable_if for controlling
// which function overload to pick based on the compile-time
// properties of the argument type.
//
// REQUIRES C++11

#include <cassert>
#include <type_traits>
#include <utility>

// a general purpose function for implicit conversions
// can be useful in different places
template <typename T, typename U>
typename 
  std::enable_if<std::is_convertible<U&&, T>::value, T>::type
convert(U && u) { return std::forward<U>(u); }
    
template <typename T>
struct optional
{
  // optional always uninitialized
  explicit operator bool() const { return false; } 
  T value() const { throw int(); }

  template <typename U>
  auto value_or(U const& v) const -> decltype(convert<T>(v))
  {
    if (*this)
      return this->value();
    else
      return v;
  }

  template <typename F>
  auto value_or(F const& f) const -> decltype(convert<T>(f()))
  {
    if (*this)
      return this->value();
    else
      return f();
  }
};

int def()
{
  return -1;
}

int main()
{
  optional<int> oi;
  assert (oi.value_or(1) == 1);
  assert (oi.value_or(&def) == -1);
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.