2
#include <bits/stdc++.h>
using namespace std;

constexpr int mod = 1e9 + 7, maxn = 2e6;
int N, M, p[1 << 10], buf[maxn];

template <bool t> struct line {
    int *v;
    int operator[](int y) const;
};       

template <> int line<0>::operator[](int y) const { return v[y]; }
template <> int line<1>::operator[](int y) const { return v[M * y]; }



What is this operator thing? Is it a function? If it is then why does it have square brackets and "const" after it? Also do these template things mean? I'm assuming that it executes one of them depending on the value of t ( true or false )'

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Tispenser
  • 23
  • 2
  • 1
    Wherever you learned `#include `, avoid that. Unless you intend to learn C++ wrong, in which case you're off to a good start. Otherwise, I recommend a [good C++ book](https://stackoverflow.com/a/388282/4641116). – Eljay May 25 '22 at 14:21
  • 1
    I recommend you get out of the habit of using [`using namespace std;`](https://stackoverflow.com/q/1452721/10077) and [`#include `](https://stackoverflow.com/q/31816095/10077). They're bad individually, but especially insidious together. – Fred Larson May 25 '22 at 14:24
  • 1
    Check out the tags I've added, and try googling the terms: [tag:templates], [tag:template-specialization], [tag:operator-overloading]. That should get you started while you wait for folks to write answers. – John Kugelman May 25 '22 at 14:24
  • The two subjects here are "class templates" and "operator overloading". Read up on those 2 chapters, and perhaps this will make more sense. – Gem Taylor May 25 '22 at 14:24
  • Thank you, everyone. This code is not written by me, I found this solution that was from a C++ contest. I was just struggling to understand its meaning – Tispenser May 25 '22 at 14:30
  • 1
    Code written for contests is never good code. It's not meant to be readable, it's not meant to be maintainable. It's meant to solve one problem fast. – Ben Voigt May 25 '22 at 15:04

1 Answers1

3

What is this operator thing? Is it a function? If it is then why does it have square brackets

You're declaring operator[] as a member function of the class template named line. By providing this, we say that we're overloading operator[] for our class template line(really for a specific class type that will be instantiated).


why does it have const after it

The const means that this operator[] member function is a const member function. Meaning we're not allowed to change the non-static non-mutable data members inside this member function.


Also do these template things mean?

Assuming you are asking about the template<> as the question title suggests, it means that you're explicitly(fully)specializing the member function operator[] for different class-template arguments 0 and 1.


More details can be found in any of the good C++ books.

Also refer to Why should I not #include <bits/stdc++.h>?.

Jason
  • 36,170
  • 5
  • 26
  • 60