The following code will compile as C, but not as C++:
#include <stdio.h>
struct somestruct {
int id;
enum {
STATE1 = 0,
STATE2,
STATE3,
STATE4,
} state;
};
int main(int argc, char *argv[])
{
static struct somestruct s;
if (s.state == STATE1) {
printf("state1\n");
}
return 0;
}
In C++, I would have to use somestruct::STATE1 (because the enum declaration is restricted to the struct/class?).
The project I'm working on is to be written in C, but currently we use some C++ libraries (Arduino), so we're compiling our c-code with a C++ compiler. So is there any way to make the above code compile in C++?
You could code it in a form that is compatible with both languages, such as:
typedef enum
{
STATE1 = 0,
STATE2,
STATE3,
STATE4,
} eState ;
struct somestruct
{
int id ;
eState state ;
};
Alternatively if you really cannot change the struct and enum definition then the following is portable (if ugly), and requires that you change every reference to the enum rather then the single definition (i.e. it has little merit IMO):
#if defined __cplusplus
#define SOMESTRUCT(e) somestruct:: e
#else
#define SOMESTRUCT(e) e
#endif
Then:
...
if (s.state == SOMESTRUCT(STATE1)) {
...
Use a using statement to bring the identifier into the calling scope:
struct somestruct {
int id;
enum {
STATE1 = 0,
STATE2,
STATE3,
STATE4,
} state;
};
#ifdef __cplusplus
using somestruct::STATE1; // <-- here
#endif
In C++, yes, exactly as you said: refer to it as somestruct::STATE1.
I don't see how you're going to be able to make this portable across both languages, but then again I don't see why you need to. Write somestruct::STATE1 in the C++ code, and STATE1 in the C code. Use macros if you really need to flip between them without duplicating code.
Don't forget to fix your broken expression s->state; s is not a pointer.
You could use a c macro definition
#define STATE1 somestruct::STATE1
That Should Allow To Go STATE1
I Would Recommend Against it since you are using a c++ compiler so you might as well make use of the c++ features that it gives you and just put somestruct::STATE1.
Related
(Not sure whether this is exclusively a C/C++ issue)
I’m currently fragmenting elements of a large Arduino project into reusable libraries - so far soo good.
However, a number of methods in the libraries return special structs which are declared in a data-types.h file contained in each library. The problem I have now is I'm unable to import/utilise these structs in my main sketch. I've tried declaring a variable of the DataTypes class in the main library header file and accessing the structs through it, but I get error error: invalid use of 'struct DataTypes::_theStructNameHere_t'
How would I go about accessing these structs from the library in my main sketch to declare as a variable type? I don't want to have to copy the header file which contains the structs from the library into my sketch, and I also don't want to have to create a separate library just for this single header file of structs!
Here's a quick example of what I mean:
Main.cpp:
#include <Arduino.h>
#include <MyLibrary.h>
MyLibrary myLib;
void setup() {
(This is declared in the library) myLib.dataTypes._theStructNameHere_t response = myLib.getASpecialValueWhichIsOfType_theStructNameHere_t()// Gives "error: invalid use of 'struct DataTypes::_theStructNameHere_t'""
// Example usage of the struct:
Serial.print("\n Loop Card Status: ");Serial.print(response.loop_status, HEX);
if (response.number_allocated > 0) {
Serial.print("\n Devices Allocated: ");Serial.print(response.number_allocated, HEX);
} else {
if (response.loop_status != 0x123) {
// Some condition
} else {
// Something else
}
}
}
void loop() {
...
}
Library Structure:
src/
- /data-types/
- - data-types.h
- MyLibrary.cpp
- MyLibrary.h
Library Header MyLibrary.h:
#ifndef _MYLIBRARY_H_
#define _MYLIBRARY_H_
#include <Arduino.h>
#include "./helpers/helpers.h"
...
#include "./data-types/data-types.h"
class MyLibrary {
public:
Uart *_commPort;
Helpers helpers;
...
DataTypes dataTypes;
DataTypes::_theStructNameHere_t getASpecialValueWhichIsOfType_theStructNameHere_t();
...
protected:
private:
};
#endif // _MYLIBRARY_H_
DataTypes Class data-types.h:
#ifndef _RESPONSE_TYPES_H
#define _RESPONSE_TYPES_H
class DataTypes
{
public:
struct _theStructNameHere_t
{
bool successful;
uint8_t loop_status;
uint8_t number_allocated;
uint8_t highest_address;
uint8_t number_inputs;
uint8_t number_outputs;
}
..even more..
private:
}
#endif // _RESPONSE_TYPES_H
I was able to obtain a MCVE from your example:
class DataTypes
{
public:
struct _theStructNameHere_t
{
};
};
class Library
{
public:
DataTypes dataTypes;
DataTypes::_theStructNameHere_t getMyDataType();
};
int main(int argc, char *argv[])
{
Library myLib;
myLib.dataTypes._theStructNameHere_t response;
}
which gives a similar error as your code:
~$ g++ test.cpp
test.cpp: In function 'int main(int, char**)':
test.cpp:20:21: error: invalid use of 'struct DataTypes::_theStructNameHere_t'
myLib.dataTypes._theStructNameHere_t response;
The problem is that you use an instance to access the struct type/name. To fix it, replace
myLib.dataTypes._theStructNameHere_t response = ...;
with
DataTypes::_theStructNameHere_t response = ...;
Notes:
Instead of using classes to create separate namespaces, please consider using namespaces directly. This is a feature of C++ which is available under Arduino.
namespace Library {
namespace DataTypes {
struct _theStructNameHere_t
{
...
};
...
} /*** namespace Library::DataTypes ***/
} /*** namespace Library ***/
Please read StackOverflow guidelines concerning how to ask a good question, in particular the section about Mininimal, Complete and Verifiable Example.
Sooner or later someone will tell you that there is no such thing as C/C++; C is C and C++ is C++; Arduino lives in its own world, even if is based on C++. Thus, you might want to remove C and C++ tags from your question.
I recently got this idea to separate different platform specific implementations (could be Win32/X, opengl/dx/vulkan, etc...) using CRTP (curiously recurring template pattern): I thought of something like this:
IDisplayDevice.h
#pragma once
#include "OSConfig.h"
namespace cbn
{
template <class TDerived> // Win32 type here
struct IDisplayDevice
{
bool run_frame(void) {
return
static_cast<const TDerived*>(this)->run_frame();
}
// a lot of other methods ...
};
}
Win32DisplayDevice.h:
#pragma once
#include "OSConfig.h"
// make sure it only gets compiled on win32/64
#if defined(CBN_OS_WINDOWS)
namespace cbn
{
class CWin32DisplayDevice
: public IDisplayDevice<CWin32DisplayDevice> {
public:
bool run_frame(void) {
call_hInstance();
call_hWnd();
#ifdef CBN_RENDERAPI_DX11
call_dx11_bufferswap();
#endif
return some_state;
}
private:
};
}
#endif
I would then provide an other implementation the same way in XDisplayDevice.h.
Finally, I would make a common interface in DisplayDevice.h:
#include "Win32DisplayDevice.h"
#include "XDisplayDevice.h"
namespace cbn
{
class CDisplayDevice
{
public:
CBN_INLINE
bool run_frame(void) { return device_->run_frame(); }
private:
#if defined(CBN_OS_WINDOWS)
CWin32DisplayDevice device_;
#elif defined(CBN_OS_LINUX)
CXDisplayDevice device_;
#elif // and so on
#else
// does nothing ...
CNillDisplayDevice device_;
#endif
}
}
So I could call it in main.cpp like:
int main()
{
CDisplayDevice my_device;
while(my_device->run_frame())
{
do_some_magic();
}
}
Do you think this would be a good way to deal with platform specific code ?
PS: I avoid victuals and polymorphism because of platform restraints (android, ps4, etc...) where pointer calls matter.
Consider this code:
struct OpenGLTraits // keep this in it's own files (.h and .cpp)
{
bool run_frame() { /* open gl specific stuff here */ }
};
struct VulkanTraits // keep this in it's own files (.h and .cpp)
{
bool run_frame() { /* vulkan specific stuff here */ }
};
template<typename T>
class DisplayDevice
{
using graphic_traits = T;
graphic_traits graphics; // maybe inject this in constructor?
void do_your_operation()
{
if(!graphics.run_frame()) // subsystem-specific call
{ ... }
}
};
This will use subsystem-specific calls, and abstract them away between a common API, without a virtual call involved. You can even inline the run_frame() implementations.
Edit (address comment question):
consider this:
#ifdef FLAG_SPECIFYING_OPEN_GL
using Device = DisplayDevice<OpenGLTraits>;
#elif FLAG_SPECIFYING_VULKAN
using Device = DisplayDevice<VulkanTraits>;
...
#endif
client code:
Device device;
device.do_your_operation();
I don't really see the benefit of CRTP here, you still have platform specific (as opposed to feature specific) ifdefs within the code, and this tends to make things harder to read and maintain. I usually prefer having different implementations in different source files - and in fact, generally having seperate directories for each platform.
such as:
platform/win64
platform/win32
platform/gnu-linux
platform/freebsd
In this way you can largely avoid the ifdef clutter, and you generally know where to find the platform specific things. You also know what you need to write in order to port things to another platform. The build system can then be made to select the correct source rather than the preprocessor.
I'm trying to wrap an existing 3rd party C++ library to a C interface, so that it can be used in bindings for another language. I'm having trouble figuring out how to wrap a namespaced enum, as opposed to just redefining it:
// Existing C++ 3rd party library header
namespace foo {
enum Fruit {
APPLE = 0,
ORANGE
}
}
So then I have my wrapped.{h,cpp} with an extern "C" block, and I just can't figure out how to export the foo::Fruit enum into the C interface
// wrapped.h
#ifdef __cplusplus
extern "C" {
#endif
// I don't want to do this
typedef enum Fruit {
APPLE = 0,
ORANGE
} Fruit;
#ifdef __cplusplus
}
#endif
#endif
Is it possible to export (mirror) foo::Fruit from the C++ library into my C wrapper as Fruit?
edit: I just noticed that you wanted to wrap an existing library without modifying it.
I fear you are about out of luck then. In general there is just no way of extracting just the enum members out of C++ code without the C compiler choking.
In practice you've got the choice whether to programmatically translate your own set of enumerations into the C++ versions in the interface, try to mirror the C++ exactly and place a bunch of static assertions to double-check, or in theory even filtering them out through scripts.
There are simply no good options here I'm afraid. For the record I would tend to prefer the first of these bad options.
Personally I probably would be lazy and just stick to the C version.
Still, if required and the number of constants is large you can do a bit of macro magic to get a single definition with C-style "namespaces" as required.
First a single header defining all enum entries through a macro:
/* Fruit.h */
FOO_ENUM(APPLE) = 0,
FOO_ENUM(ORANGE)
Then in the C header:
/* C interface */
typedef enum {
# define FOO_ENUM(id) FOO_##id
# include "Fruit.h"
# undef FOO_ENUM
} Foo_Fruit_t;
And finally in the C++ header:
// C++ interface
namespace Foo {
enum Fruit_t {
# define FOO_ENUM(id) id
# include "Fruit.h"
# undef FOO_ENUM
};
}
There are many alternatives of course. For instance if you don't mind polluting the global namespace in C++ then can always define the full enumeration directly in the C interface and copy the individual enum members in the C++ version of the definition.
I ran into this particular problem with enums in a C wrapper for a C++ library recently and it caused quite a headache.
My solution is shown in the following mostly minimal working example but it is terribly inelegant in places. It is essentially a translation approach.
One must be wary not to declare anything twice with regard to the enums. The example passes int, a string or array of char and an enum.
A library header written in C++. This is the library that will be wrapped. MyClass.h:
#ifndef __MYCLASS_H
#define __MYCLASS_H
#include <iostream>
namespace MyNamespace {
using namespace std;
enum EnumControlInterface {HIDController=1, UVCController=2};
class MyClass {
private:
int m_i;
string m_text;
EnumControlInterface _controller;
public:
MyClass(int val);
~MyClass();
void int_set(int i);
void string_set(string text);
int int_get();
string string_get();
void writeEnum(EnumControlInterface MyInterface);
EnumControlInterface readEnum();
};
};
#endif
The C++ implementation of MyClass.cpp:
#include "MyClass.h"
namespace MyNamespace {
MyClass::MyClass(int val) {
cout << "MyClass is being created" << endl;
cout << "The parameter passed to the MyClass constructor is: " << val << endl;
}
MyClass::~MyClass() {
cout << "MyClass is being destroyed" << endl;
}
void MyClass::writeEnum(EnumControlInterface MyInterface) {
_controller = MyInterface;
cout << "The interface control Enum is set in MyClass.cpp as: " << _controller << endl;
}
EnumControlInterface MyClass::readEnum() {
return _controller;
}
void MyClass::string_set(std::string text) {
m_text = text;
}
string MyClass::string_get() {
return m_text;
}
void MyClass::int_set(int i) {
m_i = i;
}
int MyClass::int_get() {
return m_i;
}
}
A "C wrapper" header file MyWrapper.h which wraps MyClass.h:
#ifndef __MYWRAPPER_H
#define __MYWRAPPER_H
#ifdef __cplusplus
namespace MyNamespace {
extern "C" {
#endif
typedef enum WrapperEnumControlInterface {WrapHIDController=1, WrapUVCController=2} WrapperEnumControlInterface;
typedef struct MyClass MyClass;
MyClass* newMyClass(int val);
void MyClass_int_set(MyClass* v, int i);
int MyClass_int_get(MyClass* v);
void MyClass_string_set(MyClass* v, char* text);
char* MyClass_string_get(MyClass* v);
void MyClass_writeEnum(MyClass* v, WrapperEnumControlInterface MyInterface);
WrapperEnumControlInterface MyClass_readEnum(MyClass* v);
void deleteMyClass(MyClass* v);
#ifdef __cplusplus
}
}
#endif
#endif
The "C wrapper" implementation is written in a mixture of C and C++. Specifically the function definitions have to be C and the parameters passed and returned have to be C types as well. Inside the functions and inside the preprocessor areas __cplusplus C or C++ should be fine.
One can not, for example, ask a function inside the extern "C" block to accept the type std::string. It would defeat the objective of the wrapper: to expose only C code that operates the underlying C++ library. extern "C" determines what is exposed without name mangling (see questions about name mangling in C++). __cplusplus is defined by (many) C++ compilers.
MyWrapper.cc:
#include "MyClass.h"
#include "MyWrapper.h"
#include <vector>
namespace MyNamespace {
extern "C" {
MyClass* newMyClass(int val) {
return new MyClass(val);
}
void deleteMyClass(MyClass* v) {
delete v;
}
void MyClass_int_set(MyClass* v, int i) {
v->int_set(i);
}
int MyClass_int_get(MyClass* v) {
return v->int_get();
}
void MyClass_string_set(MyClass* v, char* text) {
//convert incomming C char* to a C++ string
string stringToSend = string(text);
cout << "the string received from the program by the wrapper is " << text << endl;
cout << "the string sent to the library by the wrapper is " << stringToSend << endl;
v->string_set(stringToSend);
}
char* MyClass_string_get(MyClass* v) {
string result = v->string_get();
cout << "the string received from the library by the wrapper is " << result << endl;
// Convert the C++ string result to a C char pointer and return it. Use vectors to do the memory management.
// A vector type of as many chars as necessary to hold the result string
static vector<char> resultVector(result.begin(), result.end());
cout << "the data in the vector who's pointer is returned to the program by the wrapper is: " << &resultVector[0] << endl;
return (&resultVector[0]);
}
void MyClass_writeEnum(MyClass* v, WrapperEnumControlInterface MyInterface) {
v->writeEnum((EnumControlInterface)MyInterface);
}
WrapperEnumControlInterface MyClass_readEnum(MyClass* v) {
EnumControlInterface result = v->readEnum();
return (WrapperEnumControlInterface)result;
}
}
}
A C program that calls the C++ library via the wrapper Cproject.c:
#include "MyWrapper.h"
#include "stdio.h"
int main(int argc, char* argv[]) {
struct MyClass* clsptr = newMyClass(5);
MyClass_int_set(clsptr, 3);
printf("The int read back in Cproject.c is: %i\n", MyClass_int_get(clsptr));
MyClass_writeEnum(clsptr, WrapUVCController);
printf("The enum read back in Cproject.c is: %d\n", MyClass_readEnum(clsptr));
MyClass_string_set(clsptr, "Hello");
char *textReadBack = MyClass_string_get(clsptr);
printf("The text read back in Cproject.c is: %s \n", textReadBack);
deleteMyClass(clsptr);
return 0;
}
And just for completeness a C++ project that calls the C++ library directly without the use of the wrapper CPPProgram.cpp, so short!:
#include "MyClass.h"
#include <iostream>
using namespace std;
using namespace MyNamespace;
int main(int argc, char* argv[]) {
MyClass *c = new MyClass(42);
c->int_set(3);
cout << c->int_get() << endl;
c->writeEnum(HIDController);
cout << c->readEnum() << endl;
c->string_set("Hello");
cout << c->string_get() << endl;
delete c;
}
The MyClass C++ class is compiled to a static library, the wrapper is compiled to a shared library there is no particular reason, both could be static or shared.
The C program that calls the wrapper library (Cproject.c) must be linked with a C++ compiler (G++ etc.)
Obviously this example doesn't have a serious application. It is based on https://www.teddy.ch/c++_library_in_c/ in terms of structure but with the enum bits added in.
Often the person writing the wrapper doesn't have access to the source code of the library they're trying to wrap (MyClass.cpp in this case) they will have the .so or .dll or .a or .lib for Linux and Windows shared and static libraries respectively. It is not necessary to have the source code for the C++ library. Only the header file(s) for the C++ library are needed to write an effective wrapper.
I have written this out partly to provide a more verbose answer to the original question, one that can be copied compiled easily and played around with but also because this is the only way I have been able to solve the problem so far and it is not satisfactory in my view. I would like to be able to wrap the enums in the same way one wraps the public member functions not re-create the enums inside the wrapper with slightly different names.
Sources of related information that proved useful:
https://www.teddy.ch/c++_library_in_c/
How to cast / assign one enum value to another enum
Developing C wrapper API for Object-Oriented C++ code
Converting a C-style string to a C++ std::string
Returning pointer from a function
std::string to char*
Of course all unsafe, wrong etc. coding practices are my fault entirely.
In c++03 and earlier to disable compiler warning about unused parameter I usually use such code:
#define UNUSED(expr) do { (void)(expr); } while (0)
For example
int main(int argc, char *argv[])
{
UNUSED(argc);
UNUSED(argv);
return 0;
}
But macros are not best practice for c++, so.
Does any better solution appear with c++11 standard? I mean can I get rid of macros?
Thanks for all!
You can just omit the parameter names:
int main(int, char *[])
{
return 0;
}
And in the case of main, you can even omit the parameters altogether:
int main()
{
// no return implies return 0;
}
See "§ 3.6 Start and Termination" in the C++11 Standard.
There is the <tuple> in C++11, which includes the ready to use std::ignore object, that's allow us to write (very likely without imposing runtime overheads):
void f(int x)
{
std::ignore = x;
}
I have used a function with an empty body for that purpose:
template <typename T>
void ignore(T &&)
{ }
void f(int a, int b)
{
ignore(a);
ignore(b);
return;
}
I expect any serious compiler to optimize the function call away and it silences warnings for me.
To "disable" this warning, the best is to avoid writing the argument, just write the type.
void function( int, int )
{
}
or if you prefer, comment it out:
void function( int /*a*/, int /*b*/ )
{
}
You can mix named and unnamed arguments:
void function( int a, int /*b*/ )
{
}
With C++17 you have [[maybe_unused]] attribute specifier, like:
void function( [[maybe_unused]] int a, [[maybe_unused]] int b )
{
}
Nothing equivalent, no.
So you're stuck with the same old options. Are you happy to omit the names in the parameter list entirely?
int main(int, char**)
In the specific case of main, of course, you could simply omit the parameters themselves:
int main()
There are also the typical implementation-specific tricks, such as GCC's __attribute__((unused)).
What do you have against the old and standard way?
void f(int a, int b)
{
(void)a;
(void)b;
return;
}
Macros may not be ideal, but they do a good job for this particular purpose. I'd say stick to using the macro.
The Boost header <boost/core/ignore_unused.hpp> (Boost >= 1.56) defines, for this purpose, the function template boost::ignore_unused().
int fun(int foo, int bar)
{
boost::ignore_unused(bar);
#ifdef ENABLE_DEBUG_OUTPUT
if (foo < bar)
std::cerr << "warning! foo < bar";
#endif
return foo + 2;
}
PS C++17 has the [[maybe_unused]] attribute to suppresses warnings on unused entities.
There's nothing new available.
What works best for me is to comment out the parameter name in the implementation. That way, you get rid of the warning, but still retain some notion of what the parameter is (since the name is available).
Your macro (and every other cast-to-void approach) has the downside that you can actually use the parameter after using the macro. This can make code harder to maintain.
I really like using macros for this, because it allows you better control when you have different debug builds (e.g. if you want to build with asserts enabled):
#if defined(ENABLE_ASSERTS)
#define MY_ASSERT(x) assert(x)
#else
#define MY_ASSERT(x)
#end
#define MY_UNUSED(x)
#if defined(ENABLE_ASSERTS)
#define MY_USED_FOR_ASSERTS(x) x
#else
#define MY_USED_FOR_ASSERTS(x) MY_UNUSED(x)
#end
and then use it like:
int myFunc(int myInt, float MY_USED_FOR_ASSERTS(myFloat), char MY_UNUSED(myChar))
{
MY_ASSERT(myChar < 12.0f);
return myInt;
}
I have my own implementation for time critical segments of code.
I've been researching a while a time critical code for slow down and have found this implementation consumes about 2% from the time critical code i have being optimized:
#define UTILITY_UNUSED(exp) (void)(exp)
#define UTILITY_UNUSED2(e0, e1) UTILITY_UNUSED(e0); UTILITY_UNUSED(e1)
#define ASSERT_EQ(v1, v2) { UTILITY_UNUSED2(v1, v2); } (void)0
The time critical code has used the ASSERT* definitions for debug purposes, but in release it clearly has cutted out, but... Seems this one produces a bit faster code in Visual Studio 2015 Update 3:
#define UTILITY_UNUSED(exp) (void)(false ? (false ? ((void)(exp)) : (void)0) : (void)0)
#define UTILITY_UNUSED2(e0, e1) (void)(false ? (false ? ((void)(e0), (void)(e1)) : (void)0) : (void)0)
The reason is in double false ? expression. It somehow produces a bit faster code in release with maximal optimization.
I don't know why this is faster (seems a bug in compiler optimization), but it at least a better solution for that case of code.
Note:
Most important thing here is that a time critical code slow downs without above assertions or unused macroses in release. In another words the double false ? expression surprisingly helps to optimize a code.
windows.h defines UNREFERENCED_PARAMETER:
#define UNREFERENCED_PARAMETER(P) {(P) = (P);}
So you could do it like this:
#include <windows.h>
#include <stdio.h>
int main(int argc, char **argv) {
UNREFERENCED_PARAMETER(argc);
puts(argv[1]);
return 0;
}
Or outside of Windows:
#include <stdio.h>
#define UNREFERENCED_PARAMETER(P) {(P) = (P);}
int main(int argc, char **argv) {
UNREFERENCED_PARAMETER(argc);
puts(argv[1]);
return 0;
}
I am starting a new project that will be targeting MSVC, GCC (latest), GCC 4.3 ARM and more. The waf build system we have built has C++11 feature detection of the compiler.
I now have preprocessor macros for all features in compiler that I am targeting for C++11, for example #ifdef WAF_FEATURE_CXX_STRONGLY_TYPED_ENUMS. I can therefore compile different code for what the compiler supports. As GCC nearly supports it all be MSVC isn't even close (even with MSVC 11)
This got me thinking about web development polyfills - if the feature isn't available implement it with the feature set available.
This is no way near as simple as web development polyfills as for C++11 but is there anything that I can simply implement with C++03 if the compiler doesn't support it?
This boils down to the fact that I want to use strongly typed enumerators in my public API but the scoping MyClass::MyEnumerator::EnumValue will look more like MyClass::EnumValue in C++03. Is there anyway I can get the same to occur in C++03 easily:
class MyClass {
public:
#ifdef WAF_FEATURE_CXX_STRONGLY_TYPED_ENUMS
enum class MyEnumerator : unsigned int {
#else
enum MyEnumerator {
#endif
EnumValue = 0
}
void method(MyEnumerator e);
}
MyClass mc = new MyClass();
mc.method(MyClass::MyEnumerator::EnumValue) // C++11
mc.method(MyClass::EnumValue) // C++03 :(
This is what you'll need to do (I made other trivial fixes about pointers and non-pointer access).
Bsically, it's what #demi said. I had to make a dummy enum name. This works in g++-4.7.
class MyClass {
public:
#if __cplusplus > 201000
enum class MyEnumerator : unsigned int {
EnumValue = 0
};
void method(MyEnumerator e) {}
#else
class MyEnumerator {
public:
enum Dummy {
EnumValue = 0
};
};
void method(MyEnumerator::Dummy e) {}
#endif
};
int main() {
MyClass mc;
mc.method(MyClass::MyEnumerator::EnumValue); // C++11 or C++03
}
You may emulate enum class as class. Your boilerplate code will be only in definition, but usage will be same for C++11 and C++03, and may be done with templates/macros. Look answer here