C++ template class, specialized member function/operator

Started by
3 comments, last by B_old 12 years, 6 months ago
If you have a template class in C++ like this:

template<typename T> class Foo
{
T m;

operator int() const
{
return int(m);
}

//Lots of other member functions ect.
}


Is it possible to write a specialized version of that operator without writing an entire specialized version of the class?
Advertisement
I would do:



template < class T > struct FooIntConversion
{
static int doIt( const T &m ) {
return static_cast< int >( m );
}
};

template < > struct FooIntConversion< float >
{
static int doIt( float m ) {
// Do here your special case for converting float to int
return static_cast< int >( m );
}
};

template < class T > struct Foo
{
T m;

operator int() const
{
return FooIntConversion< T >::doIt( m );
}
};


But I'm sure someone with more experience would do better than me =)
You could make it virtual and override it in a derived class, but probably not the best solution, depending on what you are using it for.

template<typename T> class Foo
{
T m;

operator int() const
{
return int(m);
}

//Lots of other member functions ect.
};
template<>
Foo<int>::operator int() const
{
//specialized version
return 0;
}
Thanks everybody.
GorbGorb's solution is what I was looking for.

This topic is closed to new replies.

Advertisement