Skip to content

Instantly share code, notes, and snippets.

@Glamhoth
Created December 6, 2019 13:01
Show Gist options
  • Save Glamhoth/3a06ee1116af16c573b1039b39b1e8fc to your computer and use it in GitHub Desktop.
Save Glamhoth/3a06ee1116af16c573b1039b39b1e8fc to your computer and use it in GitHub Desktop.
#include <iostream>
template <typename T>
constexpr T
max(const T& a, const T& b)
{
return (a > b) ? a : b;
}
template <typename FIND, typename T, typename... Ts>
struct index_type
{
static const std::size_t val = index_type<FIND, Ts...>::val + 1;
};
template <typename FIND, typename... Ts>
struct index_type<FIND, FIND, Ts...>
{
static const std::size_t val = 0;
};
template <typename T, typename... Ts>
struct max_type_size
{
static const std::size_t val = max(sizeof(T), max_type_size<Ts...>::val);
};
template <typename T>
struct max_type_size<T>
{
static const std::size_t val = sizeof(T);
};
template <typename... Ts>
class ValueHolder
{
public:
ValueHolder()
: mType(0)
, mData()
{ }
template <typename T>
ValueHolder(const T& val)
: mType(index_type<T, Ts...>::val)
{
auto dataPtr = reinterpret_cast<const char*>(&val);
std::copy(dataPtr, dataPtr + sizeof(T), mData);
}
template <typename T>
const T& operator = (const T& val)
{
mType = index_type<T, Ts...>::val;
auto dataPtr = reinterpret_cast<const char*>(&val);
std::copy(dataPtr, dataPtr + sizeof(T), mData);
return val;
}
template <typename T>
bool is()
{
return mType == index_type<T, Ts...>::val;
}
template <typename T>
T& as()
{
if(!is<T>())
{
std::cerr << "No i co robisz ziemniaku?\n";
}
return *(reinterpret_cast<T*>(mData));
}
private:
std::size_t mType;
char mData[max_type_size<Ts...>::val];
};
int
main(int argc, char** argv)
{
ValueHolder<uint8_t, int32_t> val;
val = (int32_t)62456;
if(val.is<int32_t>())
{
std::cout << "super, wartosc to: " << val.as<int32_t>() << std::endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment