designing nested template classes
I'm defining a class which has as private members pointers to templated classes. I'm having a question concerning the design of such a class. M开发者_如何学编程ore precisely, whether the outer class should be templated or not. Since, I'm initializing the private members in the constructor of the outer class, I guess, it's correct to do so. Are there any other alternatives? An example of the class declaration is given below and all suggestions are welcomed:
#include <foo.h>
#include <bar.h>
template < class FOO_TYPE, class BAR_TYPE >
class OuterClass{
public:
OuterClass(){
this->m_pFoo = new CFoo<FOO_TYPE>();
this->m_pBar = new CBar<BAR_TYPE>();
this->m_nMyInt = 0;
}
template < class FOO_TYPE >
CFoo<FOO_TYPE> * processFoo();
template < class BAR_TYPE >
CBar<BAR_TYPE> * processBar();
~OuterClass(){
delete this->m_pFoo;
delete this->m_pBar;
}
private:
int m_nMyInt;
CFoo<FOO_TYPE> * m_pFoo;
CBar<BAR_TYPE> * m_pBar;
};
That depends on the intended usage of the outer class. Your code suggests that OuterClass
can be used with different template types, so it makes sense to have it as a template, too. Actually, this kind of template argument forwarding is very common.
However, if you rather want OuterClass
to use only specific template specializations of CFoo
and CBar
, then you can just specify the desired FOO_TYPE
and BAR_TYPE
in the declaration of the corresponding members.
Within your class processFoo() and processBar() are incorrectly defined.
They are not templated functions within your class, they are specifically typed to your 1st and 2nd template parameter.
CFoo and CBar appear to be external templates.
Your class is also failing the "rule of 3" with regards to copy-construction and assignment and is not exception safe if the constructor of CBar throws (in which case your constructor will throw, your destructor will never get called and m_pFoo will never get deleted).
精彩评论