0

For example i'm making a library which provides function void foo( std::string color )

And i need to somehow tell the user of my library that function foo supports only certain values for argument color (for example only "red", "green" or "blue").

Usually i make something like this

namespace ColorValues
{
  enum values
  {
    RED,
    GREEN,
    BLUE
  }

  std::string toString( ColorValues::values value )
  {
    switch( value ) 
    {
       case RED: return "red";
       case GREEN: return "green";
       case BLUE: return "blue";
       default: return "error";
    }
  }
}

void foo( ColorValues::values value )
{
   std::string theStringINeed = ColorValues::toString( value );
}

But thats just ... too cumbersome, but i dont know any other way and cpp doesn't support string enums.

What to do?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
mr.dog
  • 315
  • 1
  • 2
  • 11
  • erm, if it's a limited set, why not just expect the enum rather than the string? – Nim Oct 07 '14 at 10:43
  • 1
    also, look at approaches taken by other libraries (for example wxWidgets, has a `wxColor` class - which can be constructed with rgb values for example) however they also define static instances, such as wxColor::RED for specific colours. – Nim Oct 07 '14 at 10:45
  • 1
    you might read up on **stringly typed code**, e.g. item 7 in Jeff Atwood's blog article ["New Programming Jargon"](http://blog.codinghorror.com/new-programming-jargon/). Jeff is one of the founders of Stack Overflow. So it's sort of fitting, I think. – Cheers and hth. - Alf Oct 07 '14 at 10:45
  • @Nim well, because i work with strings in that function (for example it creates a key-value pair in xml document. both key and value are strings, and both of them cannot be just random strings) – mr.dog Oct 07 '14 at 10:51
  • @Nim good point about the wxWidgets, i will try – mr.dog Oct 07 '14 at 10:53

0 Answers0