operator[]を.at()にする

なにがしたいか

std::vectoroperator[].at()みたいに範囲外判定をしてほしい

方法

std::vectoroperator[]を上書きする

#include <iostream>
#include <vector>
using namespace std;

template <>
vector<int>::reference vector<int>::operator[](vector<int>::size_type k) {
  return this->at(k);
}

template <>
vector<int>::const_reference vector<int>::operator[](vector<int>::size_type k) const {
  return this->at(k);
}

int main() {
  vector<int> a = { 3, 1, 4 };
  cout << a[0] << endl;
  cout << a[1] << endl;
  cout << a[2] << endl;
  cout << a[3] << endl; // error! .at()による例外が投げられる
}

クラススコープで定義されたメンバ関数であるoperator[]を特殊化することはできないっぽい?
完全特殊化でお茶をにごしている

あとがき

これをしたかったら使いそうな型全部に対して同じようなことを書く必要があるから長くなってしまうし、方法がそこまできれいじゃないので微妙...