lundi 28 septembre 2015

How to create a function that converts a Class

I'm working with SFML, and I'd like to do things like the following:

sf::Texture myTexture;
myTexture.loadFromFile("texture.png");

sf::Sprite mySprite(myTexture);
mySprite.setOrigin(myTexture.getSize() / 2.f); // <~-- error

The problem is that sf::Texture::getSize() returns a sf::Vector2<unsigned>, whilst sf::Transformable::setOrigin() expects for a sf::Vector2<float>, and they're not convertible into each other.

I thought on creating a function that would accept any sf::Vector2<T> and return an equivalent sf::Vector<U>, where T and U are both arbitrary number types, so I could rewrite that last line of code as:

// converting from 'unsigned' to 'float'
mySprite.setOrigin(toVector2<unsigned, float>(myTexture.getSize()) / 2.f);

What I have so far is the following, but it doesn't work.

// Util.h
template <typename FROM, typename TO>
sf::Vector2<TO> toVector2(const sf::Vector2<FROM> &other)
{
    return sf::Vector2<TO>(
        static_cast<TO>(other.x),
        static_cast<TO>(other.y));
}

// then ...
mySprite.setOrigin(toVector2<unsigned, float>(myTexture.getSize()) / 2.f);
// ^ no instance of function template "toVector2" matches the argument list

How could I achieve such a generic conversion?

Aucun commentaire:

Enregistrer un commentaire