Semi-private enum values

Viewed 40

Is it possible to have an enumeration where (some) members are accessible from user-code and others are reserved for the implementation?

Here is a minified example of the situation I'm trying to handle: I have a benchmarking framework where I instrument the functions given by a user. To check the sanity of execution the user should report whether execution happened correctly or not, hence a return_code enumeration is created:

enum return_code {
  ok,
  error,
  execution_timeout,
  waiting_time_exceeded
};

The last two enumerators should not be available to the user, i.e. I'm the one responsible to check if there's a timeout or the processing queue never got to executing the function on time.

My current handling of the situation is to split the enumerators in a private and public interface:

namespace detail {
  enum return_code_internal {
      ok,
      error,
      execution_timeout,
      waiting_time_exceeded
  };
}

enum return_code {
    ok,
    error
};

So return_code::ok maps to detail::return_code_internal::ok and same happens for error, while the "internal" enumerators are not visible to the user. This works but forces me to jump through hoops when converting between the two types since they are not symmetric (one has 2 members while the other has 4). Is there a better way?

P.S I know that in C++ enumerators have the same visibility. I'm looking for a technique that would simulate having two enum members as "public", while the other two are "private" (or for internal use).

1 Answers

You could use a class with static members as the enumeration. This lets you have public and private members. The only catch is you would need to grant friendship to all of the things that need access to those private variables. That could look like:

struct return_code
{
    constexpr static int ok = 0;
    constexpr static int error = 1;
private:
    constexpr static int execution_timeout = 2;
    constexpr static int waiting_time_exceeded = 3;
    
    friend xxx;
    friend yyy;
    friend zzz;
};
Related