ClickHouse/libs/libmysqlxx/include/mysqlxx/Null.h

94 lines
1.8 KiB
C++
Raw Normal View History

2014-04-08 06:51:53 +00:00
#pragma once
2011-03-09 19:18:01 +00:00
#include <mysqlxx/Exception.h>
namespace mysqlxx
{
2011-03-18 20:26:54 +00:00
struct NullType {};
const NullType null = {};
2011-03-09 19:18:01 +00:00
2011-03-18 20:26:54 +00:00
/** Класс для NULL-able типов.
* Использование:
* mysqlxx::Null<int> x = mysqlxx::null;
* std::cout << (x.isNull() ? "Ok." : "Fail.") << std::endl;
* x = 10;
*/
2011-03-09 19:18:01 +00:00
template <typename T>
class Null
{
public:
T data;
bool is_null;
2011-03-09 19:18:01 +00:00
Null() : is_null(true) {}
Null(NullType data) : is_null(true) {}
2011-03-18 20:26:54 +00:00
explicit Null(const T & data_) : data(data_), is_null(false) {}
2011-03-09 19:18:01 +00:00
operator T & ()
{
if (is_null)
throw Exception("Value is NULL");
return data;
}
operator const T & () const
{
if (is_null)
throw Exception("Value is NULL");
return data;
}
Null<T> & operator= (const T & data_) { is_null = false; data = data_; return *this; }
Null<T> & operator= (const Null<T> & other) { is_null = other.is_null; data = other.data; return *this; }
Null<T> & operator= (const NullType other) { is_null = true; data = T(); return *this; }
bool isNull() const { return is_null; }
bool operator< (const Null<T> & other) const
{
return is_null < other.is_null
|| (is_null == other.is_null && data < other.data);
}
bool operator< (const NullType other) const { return false; }
bool operator== (const Null<T> & other) const
{
return is_null == other.is_null && data == other.data;
}
2011-03-18 20:26:54 +00:00
bool operator== (const T & other) const
{
return !is_null && data == other;
}
2011-03-09 19:18:01 +00:00
bool operator== (const NullType other) const { return is_null; }
bool operator!= (const Null<T> & other) const
2011-03-09 19:18:01 +00:00
{
return !(*this == other);
}
bool operator!= (const NullType other) const { return !is_null; }
2011-03-18 20:26:54 +00:00
bool operator!= (const T & other) const
{
return is_null || data != other;
}
2011-03-09 19:18:01 +00:00
};
template<typename T>
T getValueFromNull(const Null<T> & maybe)
{
if (maybe.isNull())
return {};
return maybe;
}
2011-03-09 19:18:01 +00:00
}