views:

43

answers:

2

I am trying to understand templates better

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?

A: 

I believe it should work

CPLAT::CP_Application<CPLAT::CP_DocumentPolicy_None,CPLAT::CP_PrintPolicy_None,CPLAT::CP_UndoPolicy_None>::Init(d,p,u);
a1ex07
A: 
  1. You have a class template, not a "template class". It's a template from which classes can be generated. (There's also funtion templates. Those are templates from which functions are generated.)

  2. It takes type parameters. d, p, and u are (pointers to) objects, not types. Types are, for example, CPLAT::CP_DocumentPolicy_None, CPLAT::CP_PrintPolicy_None, and CPLAT::CP_UndoPolicy_None.
    So you should be able to do

    CP_Application< CPLAT::CP_DocumentPolicy_None
                  , CPLAT::CP_PrintPolicy_None
                  , CPLAT::CP_UndoPolicy_None > app;
    
  3. 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.

  4. Instead of having to call an Init member function, have the constructor initialize the object.

sbi