开发者

Templates in C++

开发者 https://www.devze.com 2023-01-24 21:56 出处:网络
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 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

0

精彩评论

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