user877329
user877329

Reputation: 6220

STL, GCC and explicit template instantiation

Question: Why does the code below not work?

I want to use explicit template instantiation for my project. However, when I try to instantiate a standard algorithm (std::find) it seems like I also need to instantiate some internal routine. It says:

undifined reference to Foo* std::__find<Foo const*, unsigned int>(Foo const*, 
    Foo const*, unsigned int const&, std::random_access_iterator_tag)

when I

template
Foo* std::find<Foo*,unsigned int>(Foo*,Foo*,const unsigned int&);

More precicly, I am trying to do the following:

#include <algorithm>
#include <cstdio>

class Foo
    {
    public:
        unsigned int id;
        bool operator==(unsigned int b)
            {return id==b;}
};


template
Foo* std::find<Foo*,unsigned int>(Foo*,Foo*,const unsigned int&);

int main()
    {
    Foo bar[4]={1,2,3,4};
    Foo* p_bar=std::find(bar,bar+4,3);
    printf("%p    %u\n",p_bar,*p_bar);
    return 0;
    }

And it compile using

g++ -fno-explicit-templates test.cpp

to force explicit template instantiation.

The compiler output is as follows:

ccWFduTJ.o:test.cpp:(.text$_ZSt4findIP3FoojET_S2_S2_RKT0_[Foo* std::find<Foo*, unsigned int>(Foo*, Foo*, unsigned int const&)]+0x2a): undefined reference to `Foo* std::__find<Foo*, unsigned int>(Foo*, Foo*, unsigned int const&, std::random_access_iterator_tag)'
ccWFduTJ.o:test.cpp:(.text$_ZSt4findIP3FooiET_S2_S2_RKT0_[Foo* std::find<Foo*, int>(Foo*, Foo*, int const&)]+0x2a): undefined reference to `Foo* std::__find<Foo*, int>(Foo*, Foo*, int const&, std::random_access_iterator_tag)'
collect2: ld returned 1 exit status

If it helps, here is what g++ --version outputs:

g++ (tdm-1) 4.5.2

Copyright (C) 2010 Free Software Foundation, Inc.

This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Upvotes: 0

Views: 611

Answers (1)

Grimm The Opiner
Grimm The Opiner

Reputation: 1806

Just as a quick test, this builds for me:

#include <algorithm>

using namespace std;

class Foo
{
};

template<>
Foo* std::find<Foo*, unsigned int>(Foo*, Foo*, const unsigned int& )
{
    return NULL;
}

int main( int argc, char *argv )
{
    return 0;
}

Upvotes: 0

Related Questions