开发者

Creating a swatch library

Hey all, I'm working on cleaning up my code from previous semesters.

Previously I created a 151 color swatch library in c++. However because of my time crunch and lack of experience, I created it entirely as a block of define statements. Which, for hard coding values into spots worked fine. Ho开发者_StackOverflow社区wever there are some obvious weaknesses to this approach.

What I have panned out so far, is to create a namespace 'swatch' and inside the namespace I would have an enumeration for the valid colors. I would also have a 'getSwatch' function, or something similar, that would return a vec3 (a class of mine, represents a vector of 3 elemets, with some nice functionality), and the function would use a switch statement to go through the valid swatches.

It would look something like this:

namespace swatch{

    enum color{
        red,
        blue,
        green
    }

    inline
    const vec3 getColor(const color& c){
        // Switch and return red blue or green.
    }
}

My Question: I'd like to know how you might suggest doing this? Benifits of preformance, and usability is what I'm most interested in.

Thanks in advance friends,

Happy coding.

Edit: I just changed the example to make more sense to people who don't know how I use my vec class. (i.e: Everybody but me). Also, you can just look at the other anwsers for usage. They made a good guess on passing rgb values to the constructor, thats not how I did it, but I can still follow along just fine with what you mean.


Use a lookup table:

/************* .h *************/

enum color{
    red,
    blue,
    green,

    colors_count
}

const vec3 &getColor(color c)
{
    extern const vec3 colors_table[colors_count];
    return colors_table[c];
}

/************* .cpp *************/

extern const vec3 colors_table[colors_count] = {
    vec3(255, 0, 0), // red
    vec3(0, 0, 255), // blue
    vec3(0, 255, 0), // green
};

You didn't write anything about purpose of using templates so I just eliminated them. If you explain more then I will help maybe.

// EDIT
It's very simple and very fast.
In c++, enum values are not just some identifiers, they are numbers. If you don't specify other they will be fallowing numbers starting from 0: 'red' is 0, 'blue' is 1, 'green' is 2 and 'colors_count' is 3 (see http://www.google.com/search?q=c%2B%2B+enum). You can use these numbers to index an array. Then you simply pick an item from an array at given index.


You could just use a std::map<color, vec>:

  class ColorClass {
  private:
    std::map<color, vec> colors;
    // ... etc ...

And then you have a big init function that sets it up:

  colors["red"] = new vec(0xFF, 0x00, 0x00);
  colors["blue"] = new vec(0x00, 0xFF, 0x00);
  // ... etc ...

And then your getColor function is just:

  return colors[color];

Done!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜