hackerank-30 days ofcoding-template

帅比萌擦擦* 提交于 2020-02-02 05:07:22

generic programming优点是

1.代码可重用性
2.避免函数重载
3.编写后,可以多次使用。

用法:

template <typename T> 

typename and class are interchangeable in the basic case of specifying a template:

template<class T>
class Foo
{
};

and

template<typename T>
class Foo
{
};

are equivalent.

Having said that, there are specific cases where there is a difference between typename and class.

The first one is in the case of dependent types. typename is used to declare when you are referencing a nested type that depends on another template parameter, such as the typedef in this example:

template<typename param_t>
class Foo
{
    typedef typename param_t::baz sub_t;
};

The second one you actually show in your question, though you might not realize it:

template < template < typename, typename > class Container, typename Type >

When specifying a template template, the class keyword MUST be used as above — it is not interchangeable with typename in this case (note: since C++17 both keywords are allowed in this case).

You also must use class when explicitly instantiating a template:

template class Foo<int>;

I’m sure that there are other cases that I’ve missed, but the bottom line is: these two keywords are not equivalent, and these are some common cases where you need to use one or the other.

template

template 原理

在这里插入图片描述
比较特别的是构造函数的用法

#include<iostream> 
using namespace std; 
  
template<class T, class U = char> 
class A  { 
public: 
    T x; 
    U y; 
    A() {   cout<<"Constructor Called"<<endl;   } 
}; 
  
int main()  { 
   A<char> a;  // This will call A<char, char>    
   return 0; 
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!