Sign in to follow this  
B_old

C++ template class, specialized member function/operator

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
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
[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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this