I want to write a 2d (mathematical) vector class that holds an X and Y value. I want it to have overloads for operators such as + so I can easily use it to express mathematical formulas in my code. Consider this:
template <class T>
struct Vector
{
T x, y;
inline Vector<T> operator +(const Vector& other) const
{
return {x + other.x, y + other.y};
}
};
As you can see I made use of C++11's ability to use initializer lists in return statements. However, they're still not expressions - I can't apply operations to them. And here comes my problem. I want the class to be POD. I can't define custom constructors so that I can initialize x and y via parameters. This is fine because I can use initializer lists for construction, e.g.:
Vector<int> foo = {1, 2};
However, I cannot use that when I need to construct another Vector inside of an expression (operator * isn't defined but that doesn't matter here):
Vector<int> result = (foo + {1, 2}) * 12;
As I stated before the constructor alternative is not an option. I would love to hear any input on this, because I can't think of any solutions to this problem, other than storing {1, 2} in a named variable.
Well the easiest option is to just create a temporary using aggregate initialisation:
Vector<int> result = (foo + Vector<int>{1, 2}) * 12;
Alternatively, you could do some magic with C++11's user-defined literals so that something like "1,2"_v becomes one of your objects:
Vector<int> operator "" _v(const char* literal, size_t)
{
std::stringstream literal_stream(literal);
Vector<int> vec;
literal_stream >> vec.x;
literal_stream.ignore();
literal_stream >> vec.y;
return vec;
}
You could definitely do with some format checking in here though. Then you can do:
Vector<int> result = (foo + "1,2"_v) * 12;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With