使用模板的方法嵌套结构

时间:2012-12-08 00:43:23

标签: c++ struct

我想将python嵌套的defs翻译成c ++,我正在使用嵌套的结构。

#include<iostream>
static void ffunc(int x, int y)
{
    static int x1 = x;
    static int y1 = y;
    struct g
    {
        static void gfunc(int z)
        {
            static int z1 = z;
            std::cout << x1 << y1 << z << std::endl;

            struct h
            {
                static void hfunc(int k)
                {
                    std::cout<< x1 << y1 << z1 << k <<  std::endl;
                }
            };
            h::hfunc(4);
        }
    };
    g::gfunc(3);
}
int main()
{
    ffunc(1, 2);
}

此代码工作正常。问题是,我想要模板,以便嵌套函数可以使用任何类型参数。但是,当我尝试使用模板时:

#include<iostream>
template <typename t1>
static void ffunc(t1 x, t1 y)
{
    static t1 x1 = x;
    static t1 y1 = y;
    struct g
    {
        static void gfunc(int z)
        {
            static int z1 = z;
            std::cout << x1 << y1 << z << std::endl;

            struct h
            {
                static void hfunc(int k)
                {
                    std::cout<< x1 << y1 << z1 << k <<  std::endl;
                }
            };
            h::hfunc(4);
        }
    };
    g::gfunc(3);
}
int main()
{
    ffunc(1, 2);
}

我收到错误:

/tmp/cceIMovo.o: In function `void ffunc<int>(int, int)::g::gfunc(int)':
nested.cc:(.text+0x17d): undefined reference to `y1'
nested.cc:(.text+0x183): undefined reference to `x1'
/tmp/cceIMovo.o: In function `void ffunc<int>(int, int)::g::gfunc(int)::h::hfunc(int)':
nested.cc:(.text+0x1e5): undefined reference to `z1'
nested.cc:(.text+0x1ec): undefined reference to `y1'
nested.cc:(.text+0x1f2): undefined reference to `x1'

有没有人知道我想在C ++中做什么?谢谢!

1 个答案:

答案 0 :(得分:2)

我可能错了,但这看起来像编译错误。 GCC(4.7.2)产生了这个错误,而Clang(3.1)和ICC(13.0.0)处理得很好。

尝试在其他编译器上重现此代码的最小代码:http://pastebin.com/kf2sF3NL