Generic way to cast int to enum in C++

C++CastingEnums

C++ Problem Overview


Is there a generic way to cast int to enum in C++?

If int falls in range of an enum it should return an enum value, otherwise throw an exception. Is there a way to write it generically? More than one enum type should be supported.

Background: I have an external enum type and no control over the source code. I'd like to store this value in a database and retrieve it.

C++ Solutions


Solution 1 - C++

The obvious thing is to annotate your enum:

// generic code
#include <algorithm>

template <typename T>
struct enum_traits {};

template<typename T, size_t N>
T *endof(T (&ra)[N]) {
    return ra + N;
}

template<typename T, typename ValType>
T check(ValType v) {
    typedef enum_traits<T> traits;
    const T *first = traits::enumerators;
    const T *last = endof(traits::enumerators);
    if (traits::sorted) { // probably premature optimization
        if (std::binary_search(first, last, v)) return T(v);
    } else if (std::find(first, last, v) != last) {
        return T(v);
    }
    throw "exception";
}

// "enhanced" definition of enum
enum e {
    x = 1,
    y = 4,
    z = 10,
};

template<>
struct enum_traits<e> {
    static const e enumerators[];
    static const bool sorted = true;
};
// must appear in only one TU,
// so if the above is in a header then it will need the array size
const e enum_traits<e>::enumerators[] = {x, y, z};

// usage
int main() {
    e good = check<e>(1);
    e bad = check<e>(2);
}

You need the array to be kept up to date with e, which is a nuisance if you're not the author of e. As Sjoerd says, it can probably be automated with any decent build system.

In any case, you're up against 7.2/6:

> For an enumeration where emin is the > smallest enumerator and emax is the > largest, the values of the enumeration > are the values of the underlying type > in the range bmin to bmax, where bmin > and bmax are, respectively, the > smallest and largest values of the > smallest bit-field that can store emin > and emax. It is possible to define an > enumeration that has values not > defined by any of its enumerators.

So if you aren't the author of e, you may or may not have a guarantee that valid values of e actually appear in its definition.

Solution 2 - C++

Ugly.

enum MyEnum { one = 1, two = 2 };

MyEnum to_enum(int n)
{
  switch( n )
  {
    case 1 :  return one;
    case 2 : return two;
  }
  throw something();
}

Now for the real question. Why do you need this? The code is ugly, not easy to write (*?) and not easy to maintain, and not easy to incorporate in to your code. The code it telling you that it's wrong. Why fight it?

EDIT:

Alternatively, given that enums are integral types in C++:

enum my_enum_val = static_cast<MyEnum>(my_int_val);

but this is even uglier that above, much more prone to errors, and it won't throw as you desire.

Solution 3 - C++

No- there's no introspection in C++, nor is there any built in "domain check" facility.

Solution 4 - C++

If, as you describe, the values are in a database, why not write a code generator that reads this table and creates a .h and .cpp file with both the enum and a to_enum(int) function?

Advantages:

  • Easy to add a to_string(my_enum) function.
  • Little maintenance required
  • Database and code are in synch

Solution 5 - C++

What do you think about this one?

#include <iostream>
#include <stdexcept>
#include <set>
#include <string>

using namespace std;

template<typename T>
class Enum
{
public:
	static void insert(int value)
	{
		_set.insert(value);
	}
	
	static T buildFrom(int value)
	{
		if (_set.find(value) != _set.end()) {
			T retval;
			retval.assign(value);
			return retval;
		}
		throw std::runtime_error("unexpected value");
	}
	
	operator int() const { return _value; }
		
private:
	void assign(int value)
	{
		_value = value;
	}
	
	int _value;
	static std::set<int> _set;
};

template<typename T> std::set<int> Enum<T>::_set;

class Apples: public Enum<Apples> {};
	
class Oranges: public Enum<Oranges> {};

class Proxy
{
public:
	Proxy(int value): _value(value) {}
		
	template<typename T>
	operator T()
	{
		T theEnum;
		return theEnum.buildFrom(_value);
	}
	
	int _value;
};

Proxy convert(int value)
{
	return Proxy(value);
}

int main()
{	 
	Apples::insert(4);
	Apples::insert(8);
	
	Apples a = convert(4); // works
	std::cout << a << std::endl; // prints 4
	
	try {
		Apples b = convert(9); // throws	
	}
	catch (std::exception const& e) {
		std::cout << e.what() << std::endl; // prints "unexpected value"
	}
	try {
		Oranges b = convert(4); // also throws	
	}
	catch (std::exception const& e) {
		std::cout << e.what() << std::endl; // prints "unexpected value"
	}
}

You could then use code I posted here to switch on values.

Solution 6 - C++

You should not want something like what you describe to exist, I fear there are problems in your code design.

Also, you assume that enums come in a range, but that's not always the case:

enum Flags { one = 1, two = 2, four = 4, eigh = 8, big = 2000000000 };

This is not in a range: even if it was possible, are you supposed to check every integer from 0 to 2^n to see if they match some enum's value?

Solution 7 - C++

If you are prepared to list your enum values as template parameters you can do this in C++ 11 with varadic templates. You can look at this as a good thing, allowing you to accept subsets of the valid enum values in different contexts; often useful when parsing codes from external sources.

Perhaps not quite as generic as you'd like, but the checking code itself is generalised, you just need to specify the set of values. This approach handles gaps, arbitrary values, etc.

template<typename EnumType, EnumType... Values> class EnumCheck;

template<typename EnumType> class EnumCheck<EnumType>
{
public:
    template<typename IntType>
    static bool constexpr is_value(IntType) { return false; }
};

template<typename EnumType, EnumType V, EnumType... Next>
class EnumCheck<EnumType, V, Next...> : private EnumCheck<EnumType, Next...>
{
    using super = EnumCheck<EnumType, Next...>;

public:
    template<typename IntType>
    static bool constexpr is_value(IntType v)
    {
        return v == static_cast<typename std::underlying_type<EnumType>::type>(V) || super::is_value(v);
    }

    EnumType convert(IntType v)
    {
        if (!is_value(v)) throw std::runtime_error("Enum value out of range");
        return static_cast<EnumType>(v);
};

enum class Test {
    A = 1,
    C = 3,
    E = 5
};

using TestCheck = EnumCheck<Test, Test::A, Test::C, Test::E>;

void check_value(int v)
{
    if (TestCheck::is_value(v))
        printf("%d is OK\n", v);
    else
        printf("%d is not OK\n", v);
}

int main()
{
    for (int i = 0; i < 10; ++i)
        check_value(i);
}

Solution 8 - C++

C++0x alternative to the "ugly" version, allows for multiple enums. Uses initializer lists rather than switches, a bit cleaner IMO. Unfortunately, this doesn't work around the need to hard-code the enum values.

#include <cassert>	// assert

namespace  // unnamed namespace
{
	enum class e1 { value_1 = 1, value_2 = 2 };
	enum class e2 { value_3 = 3, value_4 = 4 };

	template <typename T>
	int valid_enum( const int val, const T& vec )
	{
		for ( const auto item : vec )
			if ( static_cast<int>( item ) == val ) return val;

		throw std::exception( "invalid enum value!" );	// throw something useful here
	}	// valid_enum
}	// ns

int main()
{
	// generate list of valid values
	const auto e1_valid_values = { e1::value_1, e1::value_2 };
	const auto e2_valid_values = { e2::value_3, e2::value_4 };

	auto result1 = static_cast<e1>( valid_enum( 1, e1_valid_values ) );
	assert( result1 == e1::value_1 );

	auto result2 = static_cast<e2>( valid_enum( 3, e2_valid_values ) );
	assert( result2 == e2::value_3 );

	// test throw on invalid value
	try
	{
		auto result3 = static_cast<e1>( valid_enum( 9999999, e1_valid_values ) );
		assert( false );
	}
	catch ( ... )
	{
		assert( true );
	}
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLeonidView Question on Stackoverflow
Solution 1 - C++Steve JessopView Answer on Stackoverflow
Solution 2 - C++John DiblingView Answer on Stackoverflow
Solution 3 - C++lukeView Answer on Stackoverflow
Solution 4 - C++SjoerdView Answer on Stackoverflow
Solution 5 - C++SimoneView Answer on Stackoverflow
Solution 6 - C++SimoneView Answer on Stackoverflow
Solution 7 - C++janmView Answer on Stackoverflow
Solution 8 - C++TomView Answer on Stackoverflow