문제

I have a mixture of C++ classes, some of which store a state variable 0..9 as integer, others use '0' ... '9'. Currently I do:

enum { kOne = '1' };
class StoresValueAsInt {
    static int value;  // contains 0 ... 9
};
class StoresValueAsChar {
    static char value; // contains '0' ... '9'
};
class StoresValueAsChar {
    static char value;
};

template <typename X>
isOne() { return X::value == kOne; }

This allows me to write the buggy code isOne<StoresValueAsInt::value>(). Instead, I would like to have the compiler complain about this incorrect usage. I tried the following:

enum ValueInt {
    kOne = 1
};
enum ValueChar {
    kOne = '1'
};

class StoresValueAsInt {
    static ValueInt value;
};
class StoresValueAsChar {
    static ValueChar value;
};
class StoresValueAsChar2 {
    static ValueChar value;
};

However, this does not work, because kOne is visible at the namespace level, and thus it has conflicting declarations of kOne.

Is there a way to not have the enums declared in the namespace? Or a better approach here?

updated: Added what I currently do; hoping to clarify my use case.

도움이 되었습니까?

해결책

As far as best practice, I'm really not sure what you are trying to accomplish here so I can't point you in the right direction.

However, to answer your question directly: Placing the enums in seperate namespaces would solve your issue:

namespace IntVals {
   enum ValueInt {
      kOne = 1
   };
}
namespace CharVals {
   enum ValueChar {
      kOne = '1'
   };
}

class StoresValueAsInt {
   static ValueInt value;
};
class StoresValueAsChar {
   static ValueChar value;
};

Then you should be able to use the following:

StoresValueAsInt::value == CharVals::kOne

Though this is ugly, and I wish I understood better what you were going for to offer a more elegant solution than this.

다른 팁

Is there a way to not have the enums declared in the namespace? Or a better approach here?

Yes, you can differentiate your enums as below:

struct ValueInt {
  enum {  // no need to have enum Name
    kOne = 1
  };
};
struct ValueChar {
  enum {  // no need to have enum Name
    kOne = '1'
  };
};

Usage:

ValueInt::kOne;
ValueChar::kOne;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top