简体   繁体   中英

Iteration over enum class in a project

I am following this question for iterating over an enum.

enum class COLOR
{
    Blue,
    Red,
    Green,
    Purple,
    First=Blue,
    Last=Purple
};

COLOR operator++( COLOR& x ) { return x = (COLOR)(((int)(x) + 1)); }

COLOR operator*(COLOR c) {return c;}

COLOR begin(COLOR r) {return COLOR::First;}
// end iterator needs to return one past the end!
COLOR end(COLOR r)   {return COLOR(int(COLOR::Last) + 1);}

The problem is that in my project, there are many cpp and hpp files which are compiled separately. It seems the compiler needs to have direct access to implementation of operator++ . If I declare in a hpp and then implement in cpp file, I will face with error:

compiler warning: inline function 'Color operator++(Color&)' used but never defined

linker error: undefined reference to `operator++(instruction_type&)'

If I define it directly in hpp , I will face with another error

multiple definition of ...

for operator* , begin , and end in linker.

Adding the inline keyword in front of your 4 functions will allow them to be defined in the header without the multiple definition errors. For example:

inline COLOR operator*(COLOR c) {return c;}

Or you can include just the prototype in the .h file and define the functions in 1 .cpp file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM