Search code examples
c++constructorinitializer-liststdsetenum-class

How to initialize `std::set` in constructor parameter?


I have a construction that takes a std::set as a parameter.
How do I initialize the set in the constructor parameter?

Here's an minimal conceptual example. Actual implementation is much larger.

#include <set>

enum class Fruits
{
    APPLE, PEACH, BANANA, STRAWBERRY, LEMON
};

class Pie
{
public:
    Pie(const std::set<Fruits>& flavors)
        : m_flavors(flavors)
    {
    }

    std::set<Fruits> m_flavors;
};

int main()
{
    // What is syntax for initialization here?
    Pie p(std::set<Fruits> {Fruits::APPLE, Fruits::BANANA});

    return 0;
}

The objective is to be able to specify the values for set on the parameter list.

In pseudo code:

Pie p({Fruits::APPLE, Fruits::BANANA});

The above would have the effect of passing a std::set, initialized with APPLE, BANANA, to the constructor of class Pie.

This concept would be used in the following snippet:

class Fruit_Pie
: public Pie
{
  Fruit_Pie()
    : Pie(/* wish: {Fruits::APPLE, Fruits::LEMON}*/)
    { ; }
};

In the above snippet, creating an instance of std::set<Fruits> before calling the constructor is not practical. If there is a method to do this, I'm open for it.

Research:
Searching the internet resulted in examples about initializing an instance of an std::set as a separate statement, not parameter initialization.

My previous attempt at this concept was to use unsigned int and bitwise OR the values in the initializer list. I was "upgrading" to use an std::set.

Environment:
Compiler: Visual Studio 2017
Platform: Windows 10 and Windows 7


Solution

  • Your pseudocode is valid C++11 - it is calling the std::initializer_list constructor overload of std::set. live example on wandbox.org