Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested structs with methods using templates

Tags:

c++

struct

I want to translate python nested defs to c++, which I am doing using nested structs.

#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);
}

This code works fine. The problem is, I want to templates, so that the nested functions can use any type parameters. However, when I try to use templates:

#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);
}

I get the error:

/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'

Does anyone know if what I want to do is possible in c++? Thanks!

like image 492
MegaJoules Avatar asked Dec 08 '12 00:12

MegaJoules


1 Answers

I might be wrong, but this looks like a compiler bug. GCC (4.7.2) produces that error, while Clang (3.1) and ICC (13.0.0) deal just fine with it.

Minimal code for trying to reproduce this on other compilers: http://pastebin.com/kf2sF3NL

like image 133
Nikos C. Avatar answered Sep 28 '22 18:09

Nikos C.