Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

Craazer

Can templates handle floats?

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

Hi i have code here wich uses template type function whit floats but its not accurate.
  
template <class T> Count (T a,T b)
{
 return(a+b);
}
cout<<Count(5.8,3.0)<<endl; // doesnt cout 8.8

  
how do u fix that, is it bossible?

Share this post


Link to post
Share on other sites
Advertisement
i think the correct syntax for calling templates is:
Count<float>(3.8, 5.0);

otherwise it may just be defaulting to int or something bizzarro.

-me

[edited by - Palidine on November 21, 2002 3:01:50 PM]

Share this post


Link to post
Share on other sites
Templates work with any type, but I believe you need to specify the return type

    
template<class T>
T Count(T a,T b) {
return a + b;
}

If it doesn't print out 8.8 exactly, then it's due to rounding errors and there's nothing you can do. Making the plus-operation outside the template wouldn't fix it.

By the way, in your example you pass doubles to the template instead of floats.

Palidine, function template arguments can be deducted from the input values. Had the input values been integers, T would've been int and then the explicit template argument would've been necessary to get the values to be added together as floats.

[edited by - civguy on November 21, 2002 3:07:37 PM]

Share this post


Link to post
Share on other sites
quote:
Original post by civguy
Templates work with any type, but I believe you need to specify the return type


      
template<class T>
T Count(T a,T b) {
return a + b;
}




Oh yes i was missing the ''T'' type :o)

thanks it works now!

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

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

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!