• Main Page
  • Related Pages
  • Namespaces
  • Classes
  • Files
  • File List
  • File Members

ut_option.h

Go to the documentation of this file.
00001 /* -*- mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode:nil; -*- */
00002 /* AbiWord
00003  * Copyright (C) 2017 Hubert Figuière
00004  *
00005  * This program is free software; you can redistribute it and/or
00006  * modify it under the terms of the GNU General Public License
00007  * as published by the Free Software Foundation; either version 2
00008  * of the License, or (at your option) any later version.
00009  *
00010  * This program is distributed in the hope that it will be useful,
00011  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00012  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00013  * GNU General Public License for more details.
00014  *
00015  * You should have received a copy of the GNU General Public License
00016  * along with this program; if not, write to the Free Software
00017  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
00018  * 02110-1301 USA.
00019  */
00020 
00021 
00022 // an option<> template class inspired by Rust
00023 
00024 #pragma once
00025 
00026 #include <stdexcept>
00027 
00028 #include "ut_types.h"
00029 
00030 template<class T>
00031 class ABI_EXPORT UT_Option
00032 {
00033 public:
00034   typedef T data_type;
00035 
00036   UT_Option()
00037     : m_none(true)
00038   {
00039   }
00040   UT_Option(T&& data)
00041     : m_none(false)
00042     , m_data(data)
00043   {
00044   }
00045   explicit UT_Option(const T& data)
00046     : m_none(false)
00047     , m_data(data)
00048   {
00049   }
00050   template<class... Args>
00051   UT_Option(Args&&... args)
00052     : m_none(false)
00053     , m_data(args...)
00054   {
00055   }
00056 
00057   T&& unwrap()
00058   {
00059     if (m_none) {
00060       throw std::runtime_error("none option value");
00061     }
00062     m_none = true;
00063     return std::move(m_data);
00064   }
00065   T unwrap_or(const T& value)
00066   {
00067     if (m_none) {
00068       return value;
00069     }
00070     return unwrap();
00071   }
00072   bool empty() const
00073   { return m_none; }
00074   explicit operator bool() const
00075   { return !m_none; }
00076 private:
00077   bool m_none;
00078   T m_data;
00079 };

Generated on Sun Feb 14 2021 for AbiWord by  doxygen 1.7.1