views:

64

answers:

2

Basically, I have a Linked List which implements a display()function that simply loops throught he elements and prints out their values.

I wanted to do it like this:

void List::display( std::string type )
{
    switch(type)
    {
      // Do stuff...

The compiler immediately complained. My teacher said this would be because the string is not known at compile-time, resulting in an error. That explanation sounds a little iffy, but he suggested that I use enums. So I researched it and it says that explicit string to enums doesn't work. Something like

class List
{
    enum type 
    {
        HORIZONTAL = "inline"
        VERTICAL   = "normal"
    }

and then, I really don't know.

The enum type is a part of the List class, as well as the function display(). This again looks like a really crappy solution. Nevertheless, I want to know if this approach is possible.

How could I set the enum in the main function at the same time I call display()? Like so

int main( void )
{
    display("normal");

Of course, easier approaches are very welcome. In general, how do I declare/pass an enum to a function, if possible?

+1  A: 
class List
{
    enum Type
    {
        HORIZONTAL,
        VERTICAL
    };

    void display(Type type)
    {
        switch (type)
        {
            //do stuff
        }
    }
};

int main()
{
    List l;
    l.display(List::HORIZONTAL);
}
Job
That's voodoo! Pretty cool, didn't know you could do it like that. Thanks!
SoulBeaver
Does `Type` need to be public to be used as a parameter to `display`?
Mark B
No it doesn't but if you make it private, you cannot access it in `main` and thus you cannot call `display` from there.
Job
+1  A: 

Switch, in current C++, only works with integral types. You could define your enum, switch on it, and write an auxiliary function that maps the enum to string values if needed.

Example

enum E { A, B };

string E_to_string( E e )
{
  switch(e)
  {
    case A: return "apple";
    case B: return "banana";
  }
}

void display( E e )
{
  std::cout << "displaying an " << E_to_string(e) << std::endl;
  switch(e)
  {
    case A: // stuff displaying A;
    case B: // stuff displaying B;
  }
}
Peter G.