Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POD class with inline construction inside of an expression?

Tags:

c++

c++11

clang

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.

like image 439
looki Avatar asked Nov 21 '25 19:11

looki


1 Answers

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;
like image 102
Joseph Mansfield Avatar answered Nov 23 '25 10:11

Joseph Mansfield