【问题标题】:STL, GCC and explicit template instantiationSTL、GCC 和显式模板实例化
【发布时间】:2012-03-01 09:59:15
【问题描述】:

问题:为什么下面的代码不起作用?

我想为我的项目使用显式模板实例化。但是,当我尝试实例化标准算法 (std::find) 时,似乎我还需要实例化一些内部例程。它说:

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

当我

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

更准确地说,我正在尝试执行以下操作:

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

它编译使用

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

强制显式模板实例化。

编译器输出如下:

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

如果有帮助,下面是 g++ --version 的输出:

g++ (tdm-1) 4.5.2

版权所有 (C) 2010 Free Software Foundation, Inc.

这是免费软件;查看复制条件的来源。没有 保修单;甚至不是为了适销性或特定用途的适用性。

【问题讨论】:

  • 错误提到您试图将Limb const* 作为第二个参数传递,但您的显式实例化是针对该位置的Foo* - 这是故意的吗?
  • 您能告诉我们您实际调用此函数的位置吗?仅使用此代码,您尝试做的事情是非常不透明的。

标签: c++ templates gcc stl


【解决方案1】:

作为一个快速测试,这是为我构建的:

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

【讨论】:

  • 这是专业化,不是显式实例化。
猜你喜欢
  • 2013-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-25
  • 1970-01-01
  • 1970-01-01
  • 2021-05-02
  • 2021-07-18
相关资源
最近更新 更多