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:
Alternatively, you could do some magic with C++11’s user-defined literals so that something like
"1,2"_vbecomes one of your objects:You could definitely do with some format checking in here though. Then you can do: