thehan83
thehan83

Reputation: 163

What do I need to do to have both C++/CLI and unmanaged C++11 enum classes?

The new enum class type in C++11 came from the C++/CLI version with the same name but they are quite different and are causing me problems.

I have a library written in C++11 containing several structures like (really simplified here):

// File.h

enum class MyEnum : unsigned int
{
   Val1,
   Val2
};

struct MyStruct
{
    MyEnum value;
    MyStruct(MyEnum v) : value(v) {}
};

I am trying to reach this code from a C++/CLI class library to expose it to .NET. I include the file like this:

#pragma unmanaged
#include "File.h"
#pragma managed

The problem is that the enum constructor yields a compile error message like:

error C3821: 'v': managed type or function cannot be used in an unmanaged function

suggesting that the compiler still interprets the enum class as a C++/CLI enum class even though I am within the unmanaged section and it really should interpret it as a C++11 enum class. Is there anything I can do about this?

EDIT: I am using VS2012. Please let me know if VS2013 fixes this.

Upvotes: 2

Views: 920

Answers (1)

Mark Ingram
Mark Ingram

Reputation: 73673

I have the same problem in VS2013. In my case, I'm including an unmanaged enum class but the compiler is generating errors because it thinks it's a managed enum class. With the help from the comments on the question, I was able to fix it by removing all forward declarations of the enum. It looks like this is a compiler bug, where the forward declaration ignores the #pragma unmanaged directive.

I've created an example of how to reproduce the bug here:

#pragma managed(push, off)

enum class TestEnum
{
    One,
    Two,
    Three,
};

#include <vector>

enum class TestEnum; // Forward declaration after actual declaration causes the bug

#pragma managed(pop)

int main(array<System::String ^> ^args)
{
    // error C3699: '&&' : cannot use this indirection on type 'TestEnum'
    std::vector<TestEnum> enums;

    return 0;
}

I've reported the issue to Microsoft here:
https://connect.microsoft.com/VisualStudio/feedback/details/1218131

Upvotes: 2

Related Questions