1

I am trying to do a simple library where the object is a point on the xy-axis.

I want to be able to use literals like this:

Point a = (3,4);

where (3,4) is a point literal.

I read about user defined literals, but (as I understood) this seems to be impossible.

May be "(3,4)"_P is possible as I understand it.

However, I found on this page interesting use of user defined literals as follows:

#include <iostream>
#include <complex>

int main()
{
    using namespace std::complex_literals;
    std::complex<double> c = 1.0 + 1i;
    std::cout << "abs" << c << " = " << abs(c) << '\n';
}

I can under stand the part 1i as a user defined literal, but not the whole thing 1.0 + 1i.

What I am missing, and what is the nearest possible way of getting a literal similar to (x,y) without using ".

Kamal Zidan
  • 474
  • 2
  • 9

3 Answers3

3

As Some programmer dude shows, the best way is to use uniform initialization.

However, just for the fun of it, you can (sort of) do this with User Defined Literals. My idea is to to have 2 literals for each coordinate and overload operator+ between them to create the point.

Remember, this is just for fun, don't use this in a real code:

struct Px { int x; };
struct Py { int y; };

struct Point {
    int x;
    int y;
};

constexpr auto operator""_px(unsigned long long x) -> Px { return Px{(int)x}; }
constexpr auto operator""_py(unsigned long long y) -> Py { return Py{(int)y}; }

constexpr auto operator+(Px x, Py y) -> Point { return Point{x.x, y.y}; }

then you can have:

auto p = 3_px + 4_py; // p is deduced to type `Point`

Of course this is just a rough framework. Read this great article to learn more about UDLs. You would need to deal with the narrowing conversion in a better way and propper use namespaces to make it a better solution.

As a bonus, you could also use operator, to create a syntax more appropriate to what you had in mind. But, don't do this, as overloading operator, is just evil:

auto operator,(Px x, Py y) -> Point { return Point{x.x, y.y}; }
auto p = (2_px, 1_py); // p is deduced to type `Point`
bolov
  • 72,283
  • 15
  • 145
  • 224
2

You can't make up literals on your own, only create suffixes for literals. Like the shown 1i or the standard language f as in 1.0f. (See e.g. this user-defined literal reference for more information.)

What you can to is to use uniform initialization doing something like

Point a = { 3, 4 };  // note the use of curly-braces

Depending on what Point is you might need to add a suitable constructor to make it work.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

You have 3 options

Point p = { 1,2 };
Point p2{ 1,2 };
Point p3(1,2);
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97