#include <iostream>
#include <set>
#include <sstream>
#include <string>
// trying to resemble the OP
template <typename VALUE>
class MultiAccessorT {
public:
typedef VALUE Value;
typedef std::set<Value> Table;
private:
Table &_tbl;
public:
MultiAccessorT(Table &tbl): _tbl(tbl) { }
typename Table::iterator operator[](const std::string &str)
{
std::cout << "using operator[](const std::string&) ";
std::istringstream cvt(str);
Value value;
return cvt >> value ? _tbl.find(value) : _tbl.end();
}
typename Table::iterator operator[](long value)
{
std::cout << "using operator[](long) ";
return _tbl.find((Value)value);
}
typename Table::iterator operator[](double value)
{
std::cout << "using operator[](double) ";
return _tbl.find((Value)value);
}
typename Table::iterator operator[](char value)
{
std::cout << "using operator[](char) ";
return _tbl.find((Value)value);
}
// This resembles my personal "hair-killer":
typename Table::iterator operator[](bool value)
{
std::cout << "using operator[](bool) ";
return value ? _tbl.begin() : _tbl.end();
}
};
// checking out
int main()
{
// build some sample data
std::set<unsigned> tbl = { 0, 2, 4, 6, 8, 10, 12, 14 };
// template instance and instance
MultiAccessorT<unsigned> acc(tbl);
// test the operators
std::cout << "MultiAccessorT::operator[](const string&): ";
std::cout << (acc[std::string("6")] != tbl.end() ? "found." : "missed!") << std::endl;
std::cout << "MultiAccessorT::operator[](long): ";
std::cout << (acc[6L] != tbl.end() ? "found." : "missed!") << std::endl;
std::cout << "MultiAccessorT::operator[](double): ";
std::cout << (acc[6.0] != tbl.end() ? "found." : "missed!") << std::endl;
std::cout << "MultiAccessorT::operator[](char): ";
std::cout << (acc['\6'] != tbl.end() ? "found." : "missed!") << std::endl;
// examples which force conversion
std::cout << "using a constant string \"6\" (type const char[2]) ";
std::cout << (acc["6"] != tbl.end() ? "found." : "missed!") << std::endl;
/* FAILS:
std::cout << "using a int constant 6";
std::cout << (acc[6] != tbl.end() ? "found." : "missed!") << std::endl;
g++ error: ambiguous overload for 'operator[]' (operand types are 'MultiAccessorT<unsigned int>' and 'int')
Found candidates are:
typename Table::iterator operator[](long value)
typename Table::iterator operator[](double value)
typename Table::iterator operator[](char value)
*/
// done
return 0;
}