Question

As the support of C++/CLI was really bad in 2010 (no wizard for c++/cli!), one of my project is still VS2005 C++/CLI. Now is the time to migrate this last project. Unfortunately it comes with errors during compile time. Two of them I do not understand, because they worked perfectly before, try to compile this small snippet on VS2012:

        enum class EMyEnum
        {
            Unknown,
            NotBetter,
        };

        Array ^lEnums=Enum::GetValues(EMyEnum::typeid);
        Object ^test=lEnums->GetValue(0);
        EMyEnum t=(EMyEnum)test;  // VS2012 ERROR -> Cannot cast
        String ^thetext=t.ToString(); // VS2012 ERROR -> Left of ToString() needs object

Needless to say that in VS2005 it not only compile without error or warning, it also works as expected.

Was it helpful?

Solution

Yes, this is a problem in VS2012 and up. This is caused by the C++11 language standard adopting the enum class syntax. The C++/CLI compiler can now no longer distinguish a managed enum type from an unmanaged one. The cast from Object^ is only valid for a managed enum.

The workaround is silly but effective, you should explicitly specify the accessibility of the enum class. Something that's not legal in C++11 but valid in C++/CLI. Fix:

    private enum class EMyEnum      // Note: added private
    {
        Unknown,
        NotBetter,
    };

Or use public.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top