SFML community forums

General => Feature requests => Topic started by: korczurekk on June 20, 2016, 03:06:40 pm

Title: Adding etc. different vectors
Post by: korczurekk on June 20, 2016, 03:06:40 pm
Hi, currently to add 2 different vectors I have to cast one of them:
sf::Vector2f vect1;
sf::Vector2i vect2;

vect1 += static_cast<sf::Vector2f>(vect2);
 

What about adding templates to those operators?
Title: Re: Adding etc. different vectors
Post by: Laurent on June 20, 2016, 03:26:25 pm
This was already asked not so long ago. The problem is that you can't deduce the type of the result with C++03 code, and SFML still can't use C++11.
Title: Re: Adding etc. different vectors
Post by: korczurekk on June 20, 2016, 03:34:46 pm
Sorry, I couldn't find simillar topic.

dynamic_cast inside operator's code wouldn't solve this problem?

EDIT: Here's simple example compiled with -std=c++03 and it works, why sfml can't do this?
#include <iostream>
#include <memory>

template<typename T>
struct MyVector
{
    T x;
    T y;

    MyVector()
        : x(0),
          y(0)
    { }
    MyVector(T x, T y)
    {
        this->x = x;
        this->y = y;
    }

    template<typename U>
    MyVector<T> operator +(MyVector<U> vect)
    {
        return MyVector<T>(this->x + vect.x, this->y + vect.y);
    }

    template<typename U>
    MyVector<T> & operator=(MyVector<U> vect)
    {
        x = static_cast<T>(vect.x);
        y = static_cast<T>(vect.y);
    }

    template<typename U>
    MyVector<T> & operator+=(MyVector<U> vect)
    {
        return (*this) = (*this) + vect;
    }
};

int main()
{
    MyVector<float> fVec(2.4f, 3.9f);
    MyVector<int>   iVec(5, 5);

    iVec += fVec;

    std::cout << "[" << iVec.x << " " << iVec.y << "]" << std::endl;


    return 0;
}
 
Title: Re: Adding etc. different vectors
Post by: Laurent on June 20, 2016, 06:50:28 pm
You can't assume that T + U = T. The rules are clearly defined by the language and depend on the types involved. For example, int + float = float. That's why you need C++11 with its decltype keyword.
Title: Re: Adding etc. different vectors
Post by: Nexus on June 26, 2016, 11:25:47 am
Apart from the technical limitations mentioned by Laurent, I'm not sure if it would be wise to enable such semantics. Allowing operations on different types of vectors is similar to implicit conversions, which have been disabled by design.

How often do you need to add float and integer vectors? Such requests often indicate flaws in the logic, e.g. trying to add pixels and world coordinates. I prefer if such attempts yield a compiler error, and people who know what they're doing can still use explicit conversions. Type safety is a powerful feature.
Title: Re: Adding etc. different vectors
Post by: FRex on June 26, 2016, 05:33:17 pm
There is no need for a static cast to add two different types of vectors right now:
sf::Vector2f vect1;
sf::Vector2i vect2;

vect1 += sf::Vector2f(vect2);