Home > Mobile >  How to use the `using` keyword in gcc 10.4?
How to use the `using` keyword in gcc 10.4?

Time:01-05

I am compiling with the C-Stadard 20 using this argument: "-std=gnu 2a". Thus I thought I am able to use the using keyword as following:

void anyfunc(const foo::bar& value) {
    switch (foo:bar(value)) {
        using enum foo:bar;
        case George:
            // ...
        case Mary:
            // ...
        default:
            // ...
    }
}

But my new gcc won't compile it because it does not know the 'using' keyword:

main.cpp:69:11: error: expected nested-name-specifier before ‘enum’
   69 |     using enum foo::var;
      |           ^~~~

The gcc version I use is:

arm-linux-g  .br_real (Buildroot 2022.02.5) 10.4.0

See here my full minimal example:

#include <stdio.h>

namespace foo {
    enum class bar {
        George = 0,
        Mary,
        Martin,
        // ...
    };
}

void anyfunc(const foo::bar value) {
    // This is working
    switch (foo::bar(value)) {
        case foo::bar::George:
            printf("George");
        case foo::bar::Mary:
            printf("Mary");
        default:
            printf("Default");      
    }

    // This does not compile
    // switch (foo::bar(value)) {
    //     using enum foo::bar;
    //     case George:
    //         printf("George");
    //     case Mary:
    //         printf("Mary");
    //     default:
    //         printf("Default");       
    // }
}

int main() {
    anyfunc(foo::bar::Mary);
    // ..
}

CodePudding user response:

  • You need :: to separate the namespace from the enum class
  • You do not need to cast value into a foo::bar.

Example:

#include <iostream>

namespace foo {
    enum class bar {
        George, Mary
    };
}

void anyfunc(const foo::bar value) {  // prefer to take it by value instead
    switch (value) {                  // no cast
        using enum foo::bar;          // note ::
        case George:
            std::cout << "George\n";
            break;
        case Mary:
            std::cout << "Mary\n";
            break;
        default:
            std::cout << "default\n";
    }
}

int main() {
    anyfunc(foo::bar::Mary);
}

Output:

Mary

Note: using enum (P1099R5) was added in g 11 so you will probably not be able to use it with your arm-linux-g .br_real (Buildroot 2022.02.5) 10.4.0 compiler.

  • Related