• Advertisement
Sign in to follow this  

C++ template class, specialized member function/operator

This topic is 2385 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:

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?

Share this post


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

Share this post


Link to post
Share on other sites

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;
}

Share this post


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

  • Advertisement