【发布时间】:2016-04-13 12:58:57
【问题描述】:
当外部类具有模板参数时,我正在尝试为嵌套类提供一个外联构造函数。扭曲的是内部类仅因数据成员声明而异。下面是我的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构造函数works for me的定义中删除template<>。
标签: c++ templates constructor inner-classes