Jump to content

View more

Image of the Day

The night is still, but the invasion brings chaos. #screenshotsaturday #hanako #indiegame #gameart #ue4 #samurai https://t.co/cgILXuokoS
IOTD | Top Screenshots

The latest, straight to your Inbox.

Subscribe to GameDev.net Direct to receive the latest updates and exclusive content.


Sign up now

C++ template class, specialized member function/operator

4: Adsense

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.


  • You cannot reply to this topic
4 replies to this topic

#1 B_old   Members   

689
Like
0Likes
Like

Posted 14 October 2011 - 05:26 AM

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?

#2 MChiz   Members   

161
Like
0Likes
Like

Posted 14 October 2011 - 06:10 AM

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 =)

#3 Erik Rufelt   Members   

5901
Like
0Likes
Like

Posted 14 October 2011 - 06:12 AM

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.

#4 GorbGorb   Members   

112
Like
1Likes
Like

Posted 14 October 2011 - 07:11 AM


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;

}



#5 B_old   Members   

689
Like
0Likes
Like

Posted 14 October 2011 - 07:37 AM

Thanks everybody.
GorbGorb's solution is what I was looking for.




Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.