Sign in to follow this  

Class template vs. method template. Difference?

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

What's difference between this:
template<typename T>
class MyClass
{
public:
    void MyMethod(T t) { /* ... */ }
};
and this:
class MyClass
{
public:
    template<typename T>
    void MyMethod(T t) { /* ... */ }
};

Share this post


Link to post
Share on other sites
Here's how you'd use the first one:

MyClass< int > mc1;
mc1.MyMethod( 4 );
mc1.MyMethod( 20.0 ); //20.0 gets cast to an integer
mc1.MyMethod< double > ( 20.0 ); //ERROR: MyMethod is not a templatized thingamajig. T is defined at the variable's decleration.


Whereas here's how you'd use the second one:

MyClass mc2;
mc2.MyMethod< int >( 4 );
mc2.MyMethod< int >( 20.0 ); //20.0 gets cast to an integer
mc2.MyMethod( 20.0 ); //calls mc2.MyMethod< double >( 20.0 );

MyClass< int > mc3; //ERROR: MyClass is not a templatized thingamajig. T is defined only for MyMethod, and only as it's called.

Share this post


Link to post
Share on other sites

This topic is 4840 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.

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