Templates in C++
can we declare a template
function in a normal class with out a template class or is it should be always insi开发者_运维百科de a template class
?
can we declare a template function in a normal class with out a template class
Yes we can. For example
class demo
{
public:
template <typename T>
void func(const T& x) {
//do stuffs
}
};
int main()
{
demo d;
d.func<int>(5);
}
is perfectly valid
Yes, you can have template functions in non-templated classes too, e.g.:
struct X {
template<class T>
void f(const T& t) {
// ...
}
};
Yes you can , but make sure your definition and declaration of the template function is in the header files. If you want to know more why is this like that or more about templates in general i can recommend you this book Templates - Complete Guide
精彩评论