[英]Can non-templated nested classes of class templates be implemented in a C++ header?
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
): 假设头文件
myheader.hxx
定义了一个类模板A
在其中定义了非模板类B
(不依赖于A
的template参数):
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? 在这种情况下可以在
myheader.hxx
实现B
还是可以的,或者是否需要编写一个单独的myheader.cxx
以避免链接时出现重复的定义? 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: 另外,因为它是在之前提出的,所以如果
B
碰巧有自己的模板参数,它将类似于:
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: 或者如果
B
没有,但是B::foo
做了,那就是:
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 :) 编辑 :显然,它是函数的
foo
而不是foo<T2>
,至少在GCC中(因此几乎100%确保这是标准行为)...我确定某些语言律师将能够解释原因:)
Etc. 等等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.