c++ - "template <> int line<0>::operator[](int y) const"有什么作用?

标签 c++ templates operator-overloading template-specialization

#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]; }



这个运算符是什么东西?它是一个函数吗?如果是的话为什么它后面有方括号和“const”? 这些模板还有什么意义吗?我假设它执行其中之一 取决于 t 的值( true 或 false )'

最佳答案

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

您正在声明 operator[]作为名为 line 的类模板的成员函数。通过提供此信息,我们说我们正在重载 operator[]对于我们的类模板line (实际上是针对将被实例化的特定类类型)。


why does it have const after it

const意味着这个 operator[]成员函数是一个const 成员函数。这意味着我们不允许更改此成员函数内的非静态非可变数据成员。


Also do these template things mean?

假设您询问的是 template<>正如问题标题所示,这意味着您显式(完全)特化成员函数 operator[]对于不同的类模板参数 01 .


更多详细信息可以在任何 good C++ books 中找到。 .

另请参阅 Why should I not #include <bits/stdc++.h>? .

关于c++ - "template <> int line<0>::operator[](int y) const"有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72379364/

相关文章:

c++ - 从最低值到最大值对 STL map 进行排序

c++ - 我应该如何将 __n128 转换为 __n64x2?

c++ - 具有一个显式参数的模板

c++ - 有效地获取参数包的大小达到某个索引

c++ - std::ptr_fun 模板化类和结构的参数困难

c++ - Linux vs Windows std::map 赋值构造函数(为什么会有这样的差异?)

c++ - 如何正确离开临界区?

xcode - “CGFloat”无法转换为 ‘UInt8' 以及 Swift 和 Xcode 6 beta 4 的其他 CGFloat 问题

c++ - 如何在 C++ 中使用运算符重载来显示类(游戏板)

C++ 运算符重载?