当外部类具有模板参数时,我有一段时间试图为嵌套类提供一个外联构造函数。不同之处在于内部类仅在数据成员声明方面有所不同。下面是我的MCVE .如果它可以更小,我很抱歉。
typedef unsigned char byte;
template<class W, bool B>
struct F
{
struct G;
};
template class F<int, false>;
template class F<long, true>;
template<>
struct F<int, false>::G
{
G();
byte b[4];
};
template<>
struct F<long, true>::G
{
G();
byte b[6];
};
template<>
F<int, false>::G::G()
{
b[0] = b[1] = b[2] = b[3] = 0;
}
template<>
F<long, true>::G::G()
{
b[0] = b[1] = b[2] = b[3] = b[4] = b[5] = 0;
}
int main(int argc, char* argv[])
{
return 0;
}
从上面看,我只是想让 F::G::G
越界。
当我尝试编译它时,结果是:
test.cxx:29:1: error: template-id ‘G<>’ for ‘F<int, false>::G::G()’ does not match any template declaration
F<int, false>::G::G()
^
test.cxx:35:1: error: template-id ‘G<>’ for ‘F<long int, true>::G::G()’ does not match any template declaration
F<long, true>::G::G()
^
如何为 G
提供外联构造函数?
还有其他类似的题是关注函数的。当数据成员是痛处时,我的断开连接似乎使它正常工作。
- How to explicitly instantiate a template class that has a nested class with a friend function
- Template method of template class specialization
- Specialization of template method in partial class specialization
- 等人
这就是我想要做的。 C++ 不允许它变得如此简单,因此我不得不求助于模板特化来获取编译时声明。
template<class W, bool B>
struct F
{
struct G
{
#if (B == true)
byte b[6];
#else
byte b[4];
#endif
};
};
最佳答案
尽管 G 是模板类的内部类,但实际上它本身并不是模板类。
这会起作用:
F<int, false>::G::G()
{
b[0] = b[1] = b[2] = b[3] = 0;
}
F<long, true>::G::G()
{
b[0] = b[1] = b[2] = b[3] = b[4] = b[5] = 0;
}
当然在这种情况下,您可以省去担心构造函数的麻烦:
template<>
struct F<int, false>::G
{
byte b[4] = { 0 }; // zero - initialised
};
template<>
struct F<long, true>::G
{
byte b[6] = { 0 }; // zero - initialised
};
关于c++ - 当外部类被模板化时嵌套类的外联构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36599168/