template func in class question

A

Active8

I have an STL vector I pass to a function and I need to know what
type data is in the vector when I'm in the fuction.

class MyClass
{
template class<T>
int Myfunc(T&){int i = sizeof(T);// oops - I want sizeof(float) }
};

vector<float> vec;
MyClass mc;
mc.Myfunc(vec)

Is there any way to do this without writing separate functions for
each type of data the vector might contain? And without a 2
parameter template *class* like "template class<V, T>" ?

Thanks in advance.
 
J

Jonathan Turkanis

Active8 said:
I have an STL vector I pass to a function and I need to know what
type data is in the vector when I'm in the fuction.

class MyClass
{
template class<T>
int Myfunc(T&)

{
typedef typename T::value_type type;
// Works if you know T will always be an STL container
}
vector<float> vec;
MyClass mc;
mc.Myfunc(vec)

Jonathan
 
A

Active8

{
typedef typename T::value_type type;
^^^^^^^

I don't understand the use of "typename" above.

I would've said:

typedef T::value_type type;
// Works if you know T will always be an STL container
}

I wish I could find my Osbourne C++ ref.
 
R

Rolf Magnus

Active8 said:
^^^^^^^

I don't understand the use of "typename" above.

It tells the compiler that T::value_type is the name of a type. In C++, it's
sometimes hard for the compiler to find out whether a name that depends on
a template is actually a type or not. Therefore, the compiler assumes it's
a value unless you use the typename keyword.
I would've said:

typedef T::value_type type;

That would've been wrong, and the compiler should bail out with an error.
 
A

Active8

It tells the compiler that T::value_type is the name of a type. In C++, it's
sometimes hard for the compiler to find out whether a name that depends on
a template is actually a type or not. Therefore, the compiler assumes it's
a value unless you use the typename keyword.


That would've been wrong, and the compiler should bail out with an error.

It doesn't (VC++ 6.0) and it works, but thanks the same. That makes
sense. Maybe if I turn the warnings back on...
 
J

Jonathan Turkanis

Active8 said:
It doesn't (VC++ 6.0) and it works, but thanks the same. That makes
sense. Maybe if I turn the warnings back on...

There's little connection between what a compiler should do and what VC++ 6.0
does. ;-)

Jonathan
 

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,201
Messages
2,571,049
Members
47,655
Latest member
eizareri

Latest Threads

Top