ClickHouse/dbms/include/DB/Common/typeid_cast.h

28 lines
792 B
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#pragma once
#include <type_traits>
#include <typeinfo>
/** Проверяет совпадение типа путём сравнения typeid-ов.
* Проверяется точное совпадение типа. То есть, cast в предка будет неуспешным.
* В остальном, ведёт себя как dynamic_cast.
*/
template <typename To, typename From>
typename std::enable_if<std::is_reference<To>::value, To>::type typeid_cast(From & from)
{
if (typeid(from) == typeid(To))
return static_cast<To>(from);
else
throw std::bad_cast();
}
template <typename To, typename From>
To typeid_cast(From * from)
{
if (typeid(*from) == typeid(typename std::remove_pointer<To>::type))
return static_cast<To>(from);
else
return nullptr;
}