1

Based on this question:

"enum class" emulation or solid alternative for MSVC 10.0

I would like to ask a couple of things. Assuming this code:

struct DeletionMode_E
{
    static DeletionMode_E const Off;
    static DeletionMode_E const DirSize;
    static DeletionMode_E const FileNumberSize;
    static DeletionMode_E const DirAndFileNumberSize;

    operator int const() const { return myVal; }

private:
    explicit DeletionMode_E(const int & v) : myVal(v) { }
    const int myVal;
};

And their subsequent definitions :

    Log4Reconstruction::DeletionMode_E const Log4Reconstruction::DeletionMode_E::Off(0);
    Log4Reconstruction::DeletionMode_E const Log4Reconstruction::DeletionMode_E::DirSize(1);
    Log4Reconstruction::DeletionMode_E const Log4Reconstruction::DeletionMode_E::FileNumberSize(2);
    Log4Reconstruction::DeletionMode_E const Log4Reconstruction::DeletionMode_E::DirAndFileNumberSize(3);

One can use this like :

    void Log4Reconstruction::setDeletionMode( Log4Reconstruction::DeletionMode_E const & delMode_in)
    {
        std::cout << delMode_in << std::endl;

        switch(delMode_in)
        {
        //case Log4Reconstruction::DeletionMode_E::Off: C2051 case expression not constant
        //  std::cout << "Off" << std::endl;
        //  break;
        case 1:
            std::cout << "File number" << std::endl;
            break;
        }
    }

Why is the function call operator called? How would one call it manually in order to solve the "problem" in the case statement? I am using MSVS 2008 no external libs are available.

Community
  • 1
  • 1
FailedDev
  • 26,680
  • 9
  • 53
  • 73

2 Answers2

3

There is no function-call operator declared here.

operator int const() const { return myVal; }

Is a user-defined conversion which converts an object of type DeletionMode_E to a constant integer. To invoke it, you have to perform a cast (this is done implicitly in your switch-statement).

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
2

In C++03, a function call cannot occur in a constant expression (such as a case label), so it's a no-go. In C++11, you would simply have to mark the conversion function and constructor as constexpr.

I'm not sure what you mean by "function call operator." If you mean the function operator int const() (the conversion function), it is called because the switch statement expects an integral expression, so the conversion function is used to perform the conversion — that's what they do. Incidentally, the first const is useless and it should be operator int() const { return myVal; }. To call it manually, just use its name in the usual syntax: delMode_in.operator int const().

The _E suffix seems to indicate emulation of some aspects of enumerations. Why not just use an enum?

Potatoswatter
  • 134,909
  • 25
  • 265
  • 421