How to separate inner class of template class into other file
I want to do:
typedef MyTemplateClass<Type01, Type02> TClass;
TClass t;
TClass::InnerClass i;
i.test();
i think the solution could be:
template <typename A, typename B>
class MyTemplateClass
{
public:
class InnerClass
{
//here I can do stuff with A and B
A test() { return 0; }
};
friend class InnerClass;
};
but I want to have ma templates in separate *.inl file included at the bottom of header file
how to define such behaviour in other file?
when i do just
//file.inl
class InnerClass
{
//here I can do stuff with A and B
A test() { return 0; }
};
A and B are undefined.
but
template <typename A, typename B>
class InnerClass
{
...
};
makes my method template independent of MyTemplateClass types...
开发者_如何学COnce again in one sentence: How to make InnerClass of MyTemplateClass in other file with providing
TClass::InnerClass i;
i.test();
behaviour?
It works the same as when using a non-template: you have to fully qualify the name of the member:
struct outer {
struct nested;
};
struct outer::nested {
int
test();
};
int
outer::nested::test()
{ /* whatever */ }
In your case that'd be:
template <typename A, typename B>
class MyTemplateClass {
public:
class InnerClass;
friend class InnerClass;
};
// note the use of the <> brackets
template<typename A, typename B>
class MyTemplateClass<A, B>::InnerClass {
public:
A
test();
};
// ditto
template<typename A, typename B>
A
MyTemplateClass<A, B>::InnerClass::test()
{ return 0; }
You do have to be wary of the definition order though: if e.g. MyTemplateClass
has function members that use InnerClass
, then the definition of InnerClass
has to be visible at the point of use.
Simple rule of thumb: inline everything or nothing. Either you define everything inline (the InnerClass
class definition and the function members of both classes) inside MyTemplateClass
, or you put all the definitions of all function members (of both MyTemplateClass
and InnerClass
) at the very end after InnerClass
has been defined.
Don't fret though, if you mess up your compiler will only be too happy to help you with error messages.
You can't. In a nutshell. Templates must be wholly defined before instantiation- that means that whatever you do, you'll have to define the inner class in the template class anyway.
精彩评论