【问题标题】:Out-of-line constructor for nested class when outer class is templated模板化外部类时嵌套类的外联构造函数
【发布时间】: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 提供外联构造函数?


还有其他类似的问题集中在函数上。当数据成员是痛处时,我的断开连接似乎可以正常工作。


这就是我想要做的。 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&lt;&gt;。

标签: c++ templates constructor inner-classes


【解决方案1】:

尽管 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
};

【讨论】:

  • 非常感谢。我实际上走了另一条路——试图进一步模板G,以及像template&lt;&gt; template&lt;&gt; ... 这样的C++ 愚蠢。我可以尖叫我浪费了多少时间......
猜你喜欢
  • 2015-07-03
  • 1970-01-01
  • 1970-01-01
  • 2016-10-07
  • 1970-01-01
  • 1970-01-01
  • 2014-05-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多