jburn7
jburn7

Reputation: 125

C++ How to give a parameter a specific enumeration it can be?

How do I give a parameter a list of values it is allowed to be passed as? Here is an example function:

void GamePiece::Rotate(int z){
    int x, y;
    for(int i = 0; i < 4; i++){
        x = pieceRectangles_[i].getPosition().y * z;
        y = pieceRectangles_[i].getPosition().x;
    }
}

I want z to be either 1 or negative 1. Besides if statements, how do I ensure this?

Upvotes: 0

Views: 93

Answers (4)

user2249683
user2249683

Reputation:

It appears to me you are doing a 90′ degree rotation in 2D around a virtual normal (axis) in a positive or negative Z direction:

#include <iostream>

struct Point
{
    int x;
    int y;

    Point(int x, int y)
    :   x(x), y(y)
    {}
};

struct VirtualNormalZ
{
    int value;
    VirtualNormalZ(int value)
    :   value(0 <= value ? 1 : -1)
    {}
};

// CCW is positive
Point Rotate90Degrees(const Point p, const VirtualNormalZ& normal)
{
    return Point(p.y * -normal.value, p.x * normal.value);
}

int main()
{
    VirtualNormalZ positive_normal(123);
    Point p(1, 0);
    std::cout << "Positive:\n";
    for(unsigned i = 0; i < 4; ++i)
    {
        std::cout << p.x << ", " << p.y << '\n';
        p = Rotate90Degrees(p, positive_normal);
    }
    VirtualNormalZ negative_normal(-123);
    std::cout << "Negative:\n";
    for(unsigned i = 0; i < 4; ++i)
    {
        std::cout << p.x << ", " << p.y << '\n';
        p = Rotate90Degrees(p, negative_normal);
    }
}

Upvotes: 1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385194

Ask for a boolean or an enumerator instead, and translate this to 1 or -1 when you need it.

Upvotes: 0

Cory Kramer
Cory Kramer

Reputation: 117876

You can use an actual enum class instead of passing the value by int.

enum class ERotation { eCW = 1, eCCW = -1 };

Then your function would be

void GamePiece::Rotate(ERotation const& z){
    // ...
}

Note though, if you use a enum like this, you cannot multiply z by your positions, because there is no implicit conversion to int. So you'd have to say

const int rotation = (z == ERotation::eCW) ? 1 : -1;

Or as @rici mentioned you can explicitly cast the enum value

const int rotation = int(z);

Using enum class is typesafe and will not allow a value outside the enumeration to be passed. This is also more extensible than bool since you can have many values, instead of two.

Upvotes: 3

Slava
Slava

Reputation: 44258

Use boolean instead of int:

void GamePiece::Rotate(bool positive){
    int x, y;
    for(int i = 0; i < 4; i++){
        x = pieceRectangles_[i].getPosition().y * ( positive ? 1 : -1 );
        y = pieceRectangles_[i].getPosition().x;
    }
}

You probably should call that parameter something like clockwise, but I do not know if clockwise is +1 or -1 in your system.

Upvotes: 1

Related Questions