关键字 typename
template <typename T>
class MyClass
{
typenmae T::SubType * ptr;
...
}
- .template构件(construct)
为了消除歧义
template<typename T>
int f(T& t)
{
return t.template convert<3>(pi);
//return x.convert<3>(pi);
//return ((x.convert) < 3) > (pi);
{
使用this->
#include <iostream>
template<typename T>
calss Base
{
public:
void exit() { std::cout << "Base exit" << std::endl;}
};
template<typename T>
class Derived : public Base<T>
{
public:
void foo()
{
exit();//要不就呼叫外部的exit,要不就编译错误
this->exit();//OK
}
}
Member Template(成员模板)
class 的成员也可以是template,即可以是nested class template,也可以是member function templates
//.h
template<typename T>
class Stack
{
public:
template<typenmae T1>
Stack<T>& operator= (stack<T1> const&);
}
//.cpp
template<typename T>
template<typename T1>
Stack<T>& Stack<T>::operator= (Stack<T1> const& op1)
{
if((void*)this == (void*)&op1)
{//判断是否幅值给自己
return *this;
}
...
}
Template template parameters(双重模板)
template<typename T, template<typename elem> class CONT = std::deque>
class Stack
{...}
- 因为CONT的定义是一个class型别,必须用class来宣告它,若用typename来宣告则错误
- 由于template template parameter中的template parameter并未使用到,可以省略其名称(elem)
- function template不允许拥有template template parameters
Template template argument matching(匹配)
当试图使用上述的Stack,编译器会报错,std::deque不符合template template parameter CONT的要求。问题出在template template argument不但必须是个template,而且参数必须严格匹配它说替换的template template parameter的参数,template template argument的预设值不被考虑,因此不给出拥有预设值的引数值时,编译器会认为匹配失败。
本例问题为:std::deque template要求不止一个参数,第二个参数是个配置器(alloctor),它虽然有预设值,但当它被用来匹配CONT的参数是,其预设值被编译器强行忽略。
template<typename T, template<typename elem, typename ALLOC = std::allocator<elem>> class CONT = std::deque>
class Stack
{...}
Zero initialization(零值初始化)
template<typename T>
void foo
{
T t;//如果T是内建型别(build-in type),则x值未有定义
T t = T();
}
template<typename T>
class MyClass
{
private:
T x;
public:
MyClass() : x() {...}//这么做可以确保T为内建类型时,也能被初始化
}
为解决上述问推,可以在宣告内建型别时,明确呼叫其default建构式。
以字符串常数(string literals)作为Function template arguments
以by reference的方式传递给function templateparameters时可能有些意想不到的错误:
template<typename T>
void foo(T const& a, T const& b)
{...}
template<typename T>
void foof(T const& a, T const& b)
{...}
int main()
{
std::string s;
foo("apple", "peach");//OK
foo("apple", "tomato");//error, char const[6],char const[7]
foof("apple", "tomato");//OK,退化为相同类别
foo("apple", s);//error type difference
}
在引数推导过程中,当参数并不是一个reference型别时,array转为pointer的转型动作(退化,decay)才会发生.