• Advertisement
Sign in to follow this  

C++ template class, specialized member function/operator

This topic is 2290 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

If you have a template class in C++ like this:
[code]
template<typename T> class Foo
{
T m;

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

//Lots of other member functions ect.
}
[/code]

Is it possible to write a specialized version of that operator without writing an entire specialized version of the class?

Share this post


Link to post
Share on other sites
Advertisement
I would do:

[code]

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 );
}
};
[/code]

But I'm sure someone with more experience would do better than me =)

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
[code]
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;
}
[/code]

Share this post


Link to post
Share on other sites
Thanks everybody.
GorbGorb's solution is what I was looking for.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement