Jump to content
  • Advertisement
Sign in to follow this  
B_old

C++ template class, specialized member function/operator

This topic is 2466 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
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

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
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!