Frage

I had enum class, say

enum class Enum{
   var1, var2;
}

Now I want to add some member which depends on parameter i.e var3(int). OK, It's not for enum, so I want to change it by regular class, but my goal is to leave old code(Enum::var1 as value of type Enum) possible to compile.

I tried to do it this way(let's temporary forgot about var3, it'll be static function):

class Enum{
    public:
        const static Enum var1 = Enum(1);
        const static Enum var2 = Enum(2);
    private:
        Enum(int v):v(v){
        }
    int v;
    //operator == using v
};

But it doesn't compile because Enum has incomplete type.
I can't declare it after class because it's in header so it'll not work with multiple cpp's. Besides, it's not great idea to have public constructor here.

Any thoughts?

War es hilfreich?

Lösung

Solution 1:

For the static variable problem: declare your static variables in the class declaration:

class Enum
{
    public:
        static const Enum var1;
        static const Enum var2;
        Enum(int v):v(v)
        {
        }
    private:
        int v;
        //operator == using v
};

Then, create a source file for this class, Enum.cpp, containing:

#include "Enum.h"
const Enum Enum::var1 = Enum(1);
const Enum Enum::var2 = Enum(2);

Solution 2:

If you want it to be header-only, you can use static variables instead of class variables:

class Enum
{
    public:
        Enum(int v):v(v)
        {
        }
    private:
        int v;
};

namespace Enumeration // It is not possible to name it 'Enum'
{
    // static => local to translation unit. No linking conflict
    static const Enum var1 = Enum(1);
    static const Enum var2 = Enum(2);
}

You can see a live example here. The only drawback is that you cannot use the name of the class for the namespace.

Andere Tipps

You can write a class like this:

class Enum
{
public
    enum NestedEnum : int
    {
        var1, var2
    };

    static NestedEnum var3;

    Enum(NestedEnum value) : value(value) { }

    operator NestedEnum() const { return value; }
private:
    NestedEnum value;
};

And anywhere else you can declare:

Enum::var3 = (Enum::NestedEnum)someIntegerVariable;
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top