Suppose a header file myheader.hxx
defines a class template A
in which a non-templated class B
is defined (that does not depend on the template parameter of A
):
template<class T>
class A {
class B {
// ...
};
};
Is it okay in this case to implement B
in myheader.hxx
, or do I need to write a separate myheader.cxx
to avoid duplicate definitions at link time? Is this case handeled consistently by different compilers?
It's still either a template (or part of template, don't know the ultra-precise definitions) even if it's not the top-level template, so you need to should implement it in the header (technically, it can be in a source file if that's the only place it's used, but that probably defeats the purpose).
Note: if you're not going to implement its member functions inline with the class definition, you need syntax like:
template<typename T>
void A<T>::B::foo(...)
{
// ...
}
Also, because it's come up before, if B
happened to have its own template parameter, it would be something like:
template<typename T>
template<typename T2>
void A<T>::B<T2>::foo(...)
{
// ...
}
Not:
template<typename T, typename T2>
void A<T>::B<T2>::foo(...)
{
// ...
}
Or if B
didn't but B::foo
did, it would be:
template<typename T>
template<typename T2>
// void A<T>::B::foo<T2>(...) // not this apparently
void A<T>::B::foo(...)
{
// ...
}
EDIT : apparently it's foo
above instead of foo<T2>
for a function, at least with GCC (so almost 100% sure that's standard behavior)...I'm sure some language lawyer will be able to explain why :)
Etc.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.