3

I'm trying to explore "using" in C++, and currently I would like to convert typedef into using.

For example,

typedef enum tag_EnumType : int {
    A,
    B,
    C,
} EnumType;

And I tried to convert it as following

using EnumType = enum tag_EnumType : int {
    A,
    B,
    C,
};

However, the compilation failed. Could anyone help? Thanks in advance.

The truth is, I'm working on a giant project. Some of typedef enum could be rewritten as using, but others couldn't. Does anyone know the reason? Is it related with namespace or sth?

ghost
  • 41
  • 3
  • 1
    You ask the reason why some can be rewritten, if you provide an example you may increase the chances for an answer – MatG Jan 08 '22 at 07:39
  • @MatG thx for advice, it seems like the enum in namespace defined by using could not be rewritten, so I wonder whether it's because some special organism of C++ using – ghost Jan 08 '22 at 07:53
  • 1
    I removed my answer since I didn't realize when answering that your code actually does work. As it is now, I would say the problem is non-reproducible without details. – user17732522 Jan 08 '22 at 08:28
  • 1
    "the compilation failed" How exactly? What error messages? – Yunnosch Jan 08 '22 at 09:10
  • Cannot reproduce e.g. here: https://www.tutorialspoint.com/compile_cpp_online.php – Yunnosch Jan 08 '22 at 09:11
  • 1
    Why do you want to use `typedef` or `using` at all? Specific reason? Why don't you just write `enum EnumType : int { ... }`, which is the usual way in C++. Neither `typedef` nor `using` is needed. – Hajo Kirchhoff Jan 08 '22 at 10:56
  • Well, I've found my mistake, I didn't give the enum a type name, and used it directly as a new type. Say `using EnumType = enum : int` and `void testFunc(EnumType e)`, after the type name has been added, `using EnumType = enum EnumType : int`, everything well well. – ghost Jan 19 '22 at 08:22

1 Answers1

2

typedef enum is a C way of creating enums. If you want it the C++ way, you better write:

enum EnumType : int {
    A,
    B,
    C,
};

In C++11 and above, scoped enums are also available, that way you prevent name collisions.

 enum class EnumType : int {
    A,
    B,
    C,
};

using statements are for other typedefs, some examples:

using IntVector = std::vector<int>;
using Iterator = IntVector::Iterator;
using FuncPtr = int(*)(char, double);
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
JVApen
  • 11,008
  • 5
  • 31
  • 67