Define enum-like constants of a class without providing access to the class constructor

  c++, constants, constructor, enums, namespaces

In Java I can define enum constants that have multiple members and member functions, yet do not provide public access to the enum constructor so that the client code cannot create enums in addition to those that are already defined.

I would like to emulate this behavior in C++, and tried to do so like this:

// Card ranks of a 52-card deck
class _CardRank {
public:
    _CardRank(int val, char repr) : val{ val }, repr{ repr } {};

    int get_val() { return val; };
    char get_repr() { return repr; };

private:
    int val;
    int repr;
};

namespace CardRank {
    const _CardRank C_2(0, '2');
    const _CardRank C_3(1, '3');
    const _CardRank C_4(2, '4');
    const _CardRank C_5(3, '5');
    const _CardRank C_6(4, '6');
    const _CardRank C_7(5, '7');
    const _CardRank C_8(6, '8');
    const _CardRank C_9(7, '9');
    const _CardRank C_T(8, 'T');
    const _CardRank C_J(9, 'J');
    const _CardRank C_Q(10, 'Q');
    const _CardRank C_K(11, 'K');
    const _CardRank C_A(12, 'A');
}

This gives me the scoped constants I am looking for, the client code would however still be able to create new constants. Is there any idiomatic solution to this, or is this design pattern not valid for C++?

Source: Windows Questions C++

LEAVE A COMMENT