Passing Template parameters
I am trying to understand templates b开发者_如何学Cetter
I have a template class that starts like this in my .h:
template <class DOC_POLICY, class PRINT_POLICY, class UNDO_POLICY>
class CP_EXPORT CP_Application : public CP_Application_Imp
Now I need to initialize so in my .cpp so I do:
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);
I get an error on CPLAT::CP_Application::Init(d, p, u); that states:
error: 'template class CPLAT::CP_Application' used without template parameters
How does one pass template parameters?
I believe it should work
CPLAT::CP_Application<CPLAT::CP_DocumentPolicy_None,CPLAT::CP_PrintPolicy_None,CPLAT::CP_UndoPolicy_None>::Init(d,p,u);
You have a class template, not a "template class". It's a template from which classes can be generated. (There's also function templates. Those are templates from which functions are generated.)
It takes type parameters.
d
,p
, andu
are (pointers to) objects, not types. Types are, for example,CPLAT::CP_DocumentPolicy_None
,CPLAT::CP_PrintPolicy_None
, andCPLAT::CP_UndoPolicy_None
.
So you should be able to doCP_Application< CPLAT::CP_DocumentPolicy_None , CPLAT::CP_PrintPolicy_None , CPLAT::CP_UndoPolicy_None > app;
When you have function templates, where template parameters are also function parameters (they appear as types in the function's argument list), you can omit them in the list of actual template arguments when instantiating the template:
template< typename T > void f(T obj) {...} ... f(42); // same as f<int>(42), because 42 is of type int
This is automatic function argument deduction.
Instead of having to call an
Init
member function, have the constructor initialize the object.
精彩评论