c++ - 当外部类被模板化时嵌套类的外联构造函数

标签 c++ templates constructor inner-classes

当外部类具有模板参数时,我有一段时间试图为嵌套类提供一个外联构造函数。不同之处在于内部类仅在数据成员声明方面有所不同。下面是我的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 是模板类的内部类,但实际上它本身并不是模板类。

这会起作用:

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/

相关文章:

c++ - 将 C 样式字符串转换为整数数组

c++ - 使用递归将基数提高到它的指数 - C++

c++ - 数组大小作为构造函数参数

c++ - 检测堆栈或堆分配

c++ - 为什么我在自定义比较器时收到有关空指针的错误

c++ - 构建包时出现 Cmake 错误

templates - Tumblr 使用什么模板语言?

java - RestTemplate URI 模板语法

templates - Angular2 模板 : how to wrap contents of ngFor with DIV

c++ - 如何将 const 指针初始化为未知大小的 const 数据(需要分配)