-2

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

4
  • Did you take a closer look at initializer lists? Commented Oct 6, 2018 at 20:32
  • There is a constructor for set that takes an initializer list, can you give us the error message you get when using Pie p(std::set<Fruits> {Fruits::APPLE, Fruits::BANANA});? VS 2017 is a C++11 compiler, so it should have worked. Commented Oct 6, 2018 at 20:32
  • "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." didnt get the statement. Commented Oct 6, 2018 at 20:40
  • @GilsonPJ: In a constructor, how does one create a temporary variable within the constructor list (or before the constructor is called). This is what I'm indicating. Commented Oct 7, 2018 at 17:54

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.