POD class with inline construction inside expression?

I want to write a 2d (math) vector class that contains X and Y values. I want it to have overloads for operators like +, so I can easily use it to express math 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 took advantage of C ++ 11's ability to use initialization lists in return statements. However, they are still not expressions - I cannot operate on them. And here's my problem. I want the class to be POD. I cannot define custom constructors so that I can initialize x and y through parameters. This is ok because I can use initializer lists to construct, for example:

Vector<int> foo = {1, 2};

      

However, I cannot use this when I need to construct another vector inside an expression (the * operator is not defined, but it doesn't matter here):

Vector<int> result = (foo + {1, 2}) * 12;

      

As I said, the constructor alternative is not an option. I would love to hear any data on this, because I can't think of any solutions to this problem other than storing {1, 2} in the named variable.

+3


source to share


1 answer


Well, the easiest option is to just create a temporary using aggregate initialization:

Vector<int> result = (foo + Vector<int>{1, 2}) * 12;

      

Alternatively, you can do some magic with C ++ 11 custom literals to make something like "1,2"_v

become 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 can of course do some format checks. Then you can do:

Vector<int> result = (foo + "1,2"_v) * 12;

      

+3


source







All Articles