On 07/01/2005, Victor Bazarov wrote:
Given a template function:
template <class T>
void foo(T& value)
{
// do something with value
}
Is there any way I can tell whether the type T is an STL container?
Why do you think you need to?
See below.
For example I'd like, within foo(), to treat "value" differently in
these two cases.
typedef std::vector<bar> barVector;
barVector myBarVector;
foo(myBarVector);
int i13 = 13;
foo(i13);
Overload your function templates:
template<class T> void foo(T& v) ..
template<class T> void foo(vector<T>& v) ..
or specialise it/them.
Nice idea, and it would sort out the issue of trying to get a size from
a generic std::vector when I don't know what type it is containing.
Unfortunately my compiler doesn't like it.
The code looks a lot like this (I haven't run this snippet through the
compiler so there may be the odd typo):
template <class T> int fooCount(const T& value)
{
return(-1);
}
template <class T> int fooCount(const std::vector<T>& value)
{
return(value.size());
}
class fooBase
{
public:
virtual int GetCount()const=0;
};
template <class T> fooDerived
{
private:
T t_;
public:
virtual int GetCount()const
{
return(fooCount(t_));
}
};
Unfortunately when I try to create an instance of fooDerived like this:
typedef std::vector<bar> barVector;
fooDerived<barVector> myFooBar;
I get an error message saying "call to undefined function fooCount".
(Which is odd because you'd have thought it would have picked up the
first, more generic instance.)
I'm trying this on a fairly old compiler (Borland C++ builder 3) so I'm
not sure whether it's a C++ error or a compiler nonconformace. I will
try the above on BCB6 tomorrow.
--
Simon Elliott
http://www.ctsn.co.uk