Behavior of the local class

Discussion in 'C++' started by somenath, Jan 2, 2014.

  1. somenath

    somenath Guest

    I am not able to understand why the following program does not compile.
    #include<iostream>
    using namespace std;

    template <class T >
    void Fun(T t)
    {
    static int i = t;

    class Test {
    public:
    Test( int t1) {
    cout<<"Value = "<<i<<endl;
    }
    };
    Test tt(t);

    }


    int main(void)
    {
    Fun<int >(5);
    return 0;

    }
    Whenever I try to compile the program I get the following error
    g++ LocalClass.cpp
    /tmp/ccfEKvyT.o:LocalClass.cpp:(.text+0x2b): undefined reference to `i'
    collect2: ld returned 1 exit status


    But I am aware that local class can access the static local variable of enclosing function. The following program proves that as well.

    #include<iostream>
    using namespace std;

    void Fun(int t)
    {
    static int i=t;

    class Test {
    public:
    Test( int t1) {
    cout<<"Value = "<<i<<endl;
    }
    };
    Test tt(t);

    }

    int main(void)
    {
    Fun(5);
    return 0;

    }
    This code compile fine. Then what is going wrong with template version of the program?
     
    somenath, Jan 2, 2014
    #1
    1. Advertisements

  2. You must be using a buggy version of the compiler/linker. It compiles
    and links (and runs) just fine with VC++ 2012.
    V
     
    Victor Bazarov, Jan 2, 2014
    #2
    1. Advertisements

  3. This is known g++ bug, already reported at

    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52688

    As a workaround you can pass the referenced static variable as an
    argument, or maybe move it inside the class, or ...


    Cheers & hth.,

    - Alf
     
    Alf P. Steinbach, Jan 2, 2014
    #3
  4. somenath

    K. Frank Guest

    Hi somenath (and Alf and Victor)!

    I tried this with my copy of g++.

    For what it's worth, your code compiles and runs fine
    when I compile it with a mingw-w64 version of g++:

    C:\>g++ --version
    g++ (rubenvb-4.8-stdthread) 4.8.1 20130324 (prerelease)


    Happy New Year Hacking!


    K. Frank
     
    K. Frank, Jan 4, 2014
    #4
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.