Jump to content

  • Log In with Google      Sign In   
  • Create Account

We're offering banner ads on our site from just $5!

1. Details HERE. 2. GDNet+ Subscriptions HERE. 3. Ad upload HERE.


C++ template class, specialized member function/operator


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   -  Reputation: 666

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?

Sponsor:

#2 MChiz   Members   -  Reputation: 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   Crossbones+   -  Reputation: 3532

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   -  Reputation: 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   -  Reputation: 666

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.



PARTNERS