Template overriding of operator []
-
Hello, I have a class and I want to override its
[]
operator. So I did like this:int operator [] (LPCTSTR x)
{
.....
}Now I want my operator to return long, doubles, strings etc. I don't want to manually write dozen of operators, but handle it with templates:
template <typename T>
T operator [] (LPCTSTR x)
{
T t;
....
return t;
}This complies fine. My problem is that I don't know how to call my template operator. I tried:
MyClass m;
m["str"]<int>;
m<int>["str"];
m.operator <int>[] ("str");but all I got were compiler errors. Any ideas? Thanks Best regards, Alexandru Savescu P.S. Interested in art? Visit this!
-
Hello, I have a class and I want to override its
[]
operator. So I did like this:int operator [] (LPCTSTR x)
{
.....
}Now I want my operator to return long, doubles, strings etc. I don't want to manually write dozen of operators, but handle it with templates:
template <typename T>
T operator [] (LPCTSTR x)
{
T t;
....
return t;
}This complies fine. My problem is that I don't know how to call my template operator. I tried:
MyClass m;
m["str"]<int>;
m<int>["str"];
m.operator <int>[] ("str");but all I got were compiler errors. Any ideas? Thanks Best regards, Alexandru Savescu P.S. Interested in art? Visit this!
The syntax for calling your templatized operator is as convoluted as it can get:
m.template operator[]<int>("str");
Unfortunately, VC++ 6.0sp5 does not swallow this (don't know for other MS compilers). An alternative, that also simplifies notation, is as follows:
template <typename T>
struct Type2Type // borrowed from Alexandrescu's "Modern C++ Design"
{
typedef T type;
};struct MyClass
{
template <typename T> T operator () (const char * x,Type2Type<T>)
{
T t;
...
return t;
}
};int main()
{
MyClass m;
m("str",Type2Type<int>());
m("str",Type2Type<double>());
return 0;
}This solution alas drops the nice
[]
notation in favor of simpler parentheses, but I don't think you have a better alternative. Joaquín M López Muñoz Telefónica, Investigación y Desarrollo