传递模板参数

问题描述:

我想更好地了解模板传递模板参数

我有开始像这样在我的.h模板类:

template <class DOC_POLICY, class PRINT_POLICY, class UNDO_POLICY> 
class CP_EXPORT CP_Application : public CP_Application_Imp 

现在我需要在我的.cpp初始化如此,所以我做:

CPLAT::CP_DocumentPolicy_None * d = new CPLAT::CP_DocumentPolicy_None(); 
CPLAT::CP_PrintPolicy_None * p = new CPLAT::CP_PrintPolicy_None(); 
CPLAT::CP_UndoPolicy_None * u = new CPLAT::CP_UndoPolicy_None(); 

CPLAT::CP_Application::Init(d, p, u); 

我在CPLAT :: CP_Application :: Init(d,p,u)上得到一个错误;各国:

错误:“模板类CPLAT :: CP_Application”没有模板参数

怎样一个通模板参数使用?

我相信它应该工作

CPLAT::CP_Application<CPLAT::CP_DocumentPolicy_None,CPLAT::CP_PrintPolicy_None,CPLAT::CP_UndoPolicy_None>::Init(d,p,u); 

  1. 你有一个类模板,而不是一个 “模板类”。这是可以从中生成类的模板。 (还有函数模板。这些是从它们生成的函数的模板。)

  2. 它需要类型参数d,pu是(指向)对象,而不是类型。类型是,例如,CPLAT::CP_DocumentPolicy_NoneCPLAT::CP_PrintPolicy_NoneCPLAT::CP_UndoPolicy_None
    所以,你应该能够做到

    CP_Application< CPLAT::CP_DocumentPolicy_None 
           , CPLAT::CP_PrintPolicy_None 
           , CPLAT::CP_UndoPolicy_None > app; 
    
  3. 当你有函数模板,其中模板参数功能参数(它们出现在函数的参数列表类型),你可以忽略它们在实例化模板时的实际模板参数列表中:

    template< typename T > 
    void f(T obj) {...} 
    ... 
    f(42); // same as f<int>(42), because 42 is of type int 
    

    这是自动函数参数推导。

  4. 而不必调用Init成员函数,让构造函数初始化该对象。