Template operators

A

Alex Tibbles

quick:

struct A
{
template< typename T >
operator[](size_t index)
{
return vec_[index];
}
std::vector< int > vec_;
};

int main()
{
A a;
float f = a[1]; // doesn't specify template parameter
or
float f = a.operator()< float >(1); // gcc 3.3.2 Debian gives error
"operator[] not defined"
or what?
}

Any clues?

alex
 
P

Patrik Stellmann

Alex said:
quick:

struct A
{
template< typename T >
operator[](size_t index)
{
return vec_[index];
}
std::vector< int > vec_;
you don't even use the template parameter! I guess you mean

template< typename T >
T operator[](size_t index)
{
return vec_[index];
}
};

int main()
{
A a;
float f = a[1]; // doesn't specify template parameter
not necessary since your code doesn't use the template parameter and by
default the result is int so everythings working...
or
float f = a.operator()< float >(1); // gcc 3.3.2 Debian gives error
should be
a.operator[]<float>(1);
?
 
T

tom_usenet

quick:

struct A
{
template< typename T >
operator[](size_t index)

Did you mean:
T operator[](size_t index)
?
Or
int operator[](size_t index)
perhaps?
{
return vec_[index];
}
std::vector< int > vec_;
};

int main()
{
A a;
float f = a[1]; // doesn't specify template parameter
or
float f = a.operator()< float >(1); // gcc 3.3.2 Debian gives error
"operator[] not defined"
or what?
}

Any clues?

Ignoring the typos and missing headers,

float f = a.operator[]<float>(1);

should compile (it does on my compilers other than GCC). But why make
the operator a template anyway? It means you have to call it with
explicitly specified template parameters...

Tom

C++ FAQ: http://www.parashift.com/c++-faq-lite/
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
 

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

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,522
Members
44,995
Latest member
PinupduzSap

Latest Threads

Top