mjhalwa
mjhalwa

Reputation: 533

Abbreviated Syntax to define a std::vector of class enum values in C++

Due to my inability to find an answer or the right words to search for I ask here:

I have a (lengthy) class enum defined by

enum class SomeLongName { Foo = 1, Bar = 7, FooBar = 42 };

The only way I know to define a vector of those is:

#include <vector>

enum class SomeLongName { Foo = 1, Bar = 7, FooBar = 42 };

int main() {
  std::vector<SomeLongName> v1 = {
    SomeLongName::Foo,
    SomeLongName::FooBar
  };
  return 0;
}

Is there a way (alternative abbreviated syntax) to use a class enum and don't need to rewrite SomeLongName:: for each value independently? e.g. something like (not working)

#include <vector>

enum class SomeLongName { Foo = 1, Bar = 7, FooBar = 42 };

int main() {
  std::vector<SomeLongName> v1 = (SomeLongName::) { Foo , Bar };
  return 0;
}

In case this matters: I am using MSVC 2019, amd64 (64bit), C++17 on windows 10 64bit

Note: using a typedef like suggested in this stackoverflow discussion thread is not actually what I want or am asking for

Upvotes: 2

Views: 336

Answers (2)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122238

Pre C++20: Unfortunately no. Its a "feature" of scoped enums that you have to prepend the name of the enum type. However, before scoped enums were a thing, it was common to wrap enums in a class to avoid polluting the namespace. You can still do that:

#include <vector>

struct SomeLongName {
    enum values { Foo = 1,Bar = 7, FooBar = 42};

    static std::vector<values> make_vect() {
        return {Foo,FooBar};
    }
};

int main() {
    auto v = SomeLongName::make_vect();
}

It's not "nice" but it works.

Past C++20: I refer you to this answer.

Upvotes: 2

Argishti Ayvazyan
Argishti Ayvazyan

Reputation: 316

C++20 added using enum X syntax, which does what it looks like.

#include <vector>

enum class SomeLongName { Foo = 1, Bar = 7, FooBar = 42 };

int main()
{
    using enum SomeLongName;
    std::vector<SomeLongName> v1 = { Foo, Bar };
    return 0;
}

In previous versions, you can use an enum instead of an enum class.

Upvotes: 5

Related Questions