templating operator[]

F

frs

It is obviously possible to template the operator[]. But
how can one use it? Considering the following example,
how would I get something like 'a<int>[12]', assuming
'a' is of type 'A'. Is it my compiler that is too weak
(g++ 3.3.5) ?

Thanks and Regards

Frank

EXAMPLE:----------------------------------------------------------------
struct A {
template <typename T>
int operator[](const int&);
};

template <> int
operator[]<int>(const int& X)
{ return 0; }

template <> int
operator[]<double>(const int& X)
{ return 1; }
 
G

Gianni Mariani

frs said:
It is obviously possible to template the operator[]. But
how can one use it? Considering the following example,
how would I get something like 'a<int>[12]', assuming
'a' is of type 'A'. Is it my compiler that is too weak
(g++ 3.3.5) ?

Does this help ?

struct A {
template <typename T>
int operator[](const int&);
};

template <>
int A::eek:perator[]<int>(const int& X)
{ return 0; }

template <>
int A::eek:perator[]<double>(const int& X)
{ return 1; }


int main()
{
A a;

a.operator[]<int>( 2 );
a.operator[]<double>( 2 );

a[1]; // illegal
}
 
F

Frank Chang

Gianni, This doesn't compile on MSVC7.1. Does it compile on g++ 3.3.5?
Thank you.
 
G

Gianni Mariani

Frank said:
Gianni, This doesn't compile on MSVC7.1. Does it compile on g++ 3.3.5?
Thank you.

What errors do you get ? It does compiler (except for the line marked
illegal) on gcc 4.0.0.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,174
Messages
2,570,940
Members
47,485
Latest member
Andrewayne909

Latest Threads

Top