开发者

Is it safe to to use template for primitive / class and pointer to primitive / class?

开发者 https://www.devze.com 2023-04-06 07:00 出处:网络
template<class T> class stack { T arr[5]; }; class item{}; stack <int> obj1; stack <int *> obj2;
template<class T>
class stack {
    T arr[5];
};


class item{};


stack <int> obj1;
stack <int *> obj2;
stack <item> obj3;
stack <item *> obj4;
开发者_如何学Go

Is it a correct template implementation?


Simple Answer: Yes

Complex Answer:
As long as the type T can be default constructed (because it is used in an array within stack) then it can be used as a template parameter from stack.

So yes all the types you list will work for stack<T>

Rule of thumb: If you could manually write the class with the templated type and it still works(compiles) then it is fine to use as a template parameter.


Yes this is OK.

Don't confuse templates with macros. In macros the string is simply replaced by the preprocessor which could lead to an incorrect or unwanted result. In templates the T becomes the real type as it would have been a typedef.

You do know that STL has a stack implementation, do you (look for std::stack)?


Yes.

It is right.

Templates can be used with native types without any problem.


Yes. All of them are valid instantiation of the class template, as far as the language is concerned.

0

精彩评论

暂无评论...
验证码 换一张
取 消