What's the reason for mentioning the <T> in the definition of a template member
Why is the syntax of a template member definition written in the following way -
Code:
template <typename T>
MyList<T>::push_back(T & value) { ... }
and not
Code:
template <typename T>
MyList::push_back(T & value) { ... } // why can't it be MyList:: instead of MyList<T>::
Is there any reason for the usage of <T> immediately after the class name?
Thanks.
Re: What's the reason for mentioning the <T> in the definition of a template member
Well, what happens if you want to add a method that takes another type, T1 for example?
Re: What's the reason for mentioning the <T> in the definition of a template member
Could you give me an example, please.
Did you mean this?
Code:
template <typename T>
class MyList
{
public:
void push_back(const T & t);
template <typename T1>
void emplace_back(const T1 & t);
};
template <typename T>
void MyList<T>::push_back(T const & t)
{
cout << t << endl;
}
template <typename T>
template <typename T1>
void MyList<T>::emplace_back(const T1 & t) // Still in this case we are preceding with "template <type T>", but I don't understand the need of <T> in MyList<T>::
{
cout << "This is another type " << t << endl;
}
int main()
{
MyList<string> obj;
obj.push_back(string("rahul"));
obj.emplace_back(int(23));
}
Thanks.
Re: What's the reason for mentioning the <T> in the definition of a template member
yes, that is what I meant.
When you define a calss template, you need to specify the template type when us initialize the template.
You could get rid of the class template deceleration and have a non template class, which has only template functions, then you don't need to specify the template type on the class level.