[Development] API style guide: scoped enum or not?

André Somers andre at familiesomers.nl
Thu May 4 19:25:38 CEST 2023


On 04/05/2023 15:51, Sune Vuorela wrote:
> On 2023-05-04, Marc Mutz via Development<development at qt-project.org>  wrote:
>> that keeps unported code running. The main issue isn't the scoping, the
>> main issue will be the missing implicit conversion to underlying_type.
> In few cases the implicit conversion to underlying_type is kind of important.
>
> Especially in the cases where the api has int and is mostly used with
> enums or is somehow user extendable.
>
> Qt::ItemDataRole is one of them that comes to mind.
>
> switch(role) {
>     case Qt::UserRole+1:
>     ....

First of all, the use of Qt::UserRole+1 isn't really good practice. 
Define your roles in a scoped enum. For this use case, we have been 
using this little trick:

// Tool to convert class enum value to underlying type for easier use
template <typename E>
constexpr typename std::underlying_type<E>::type operator+(const E &e)
{
     return static_cast<typename std::underlying_type<E>::type>(e);
}

Now, we can write the switch like this:

switch (role) {
    case +Roles::Name: //...
    case +Roles::Age: //...

Of course, you can also do:

switch (static_cast<Roles>(int)) {
    case Roles::Name: //...
    case Roles::Age: //...

But AFAIK, now you need to make sure the int value actually is in the 
enum first to make that safe.

Cheers,

André
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/development/attachments/20230504/f7c9f99b/attachment.htm>


More information about the Development mailing list