Skip to content

Instantly share code, notes, and snippets.

@kyzmitch
Created September 12, 2023 19:52
Show Gist options
  • Save kyzmitch/b1350df7da5d0f7f069705cb4a1239db to your computer and use it in GitHub Desktop.
Save kyzmitch/b1350df7da5d0f7f069705cb4a1239db to your computer and use it in GitHub Desktop.
c++ meta programming example
#include <optional>
#include <string>
#include <type_traits>
/**
@tparam T must be an Enum type.
@tparam C converter must have `toString` and `fromString` static methods
*/
template<typename T,
typename C,
std::enable_if_t<std::is_enum<T>::value, bool> = true,
std::enable_if_t<std::is_invocable_r<T, decltype(C::fromString), std::string>::value, bool> = true,
std::enable_if_t<std::is_invocable_r<std::string, decltype(C::toString), T>::value, bool> = true>
class EnumString
{
T mCase;
std::string mRawValue;
public:
EnumString<T>(const T enumCase)
{
mCase = enumCase;
mRawValue = C::toString(enumCase);
}
/**
When there is no enum type it should be still possible to set raw string.
*/
EnumString<T>(const std::string& rawValue)
{
mRawValue = rawValue;
mCase = C::fromString(rawValue);
}
virtual ~EnumString() = default;
std::string rawValue() const { return mRawValue; }
T value() const { return mCase; }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment