c++ - 与字符串一起使用时对函数模板的 undefined reference (GCC)

标签 c++ string templates gcc stl

我需要在 C++ 中编写一个模板化函数 replace_all,它将接受一个字符串、wstring、glibmm::ustring 等,并替换 中所有出现的 search >subject 替换为

replace_all.cc

template < class T >
T replace_all(
        T const &search,
        T const &replace,
        T const &subject
) {
        T result;

        typename T::size_type done = 0;
        typename T::size_type pos;
        while ((pos = subject.find(search, done)) != T::npos) {
                result.append (subject, done, pos - done);
                result.append (replace);
                done = pos + search.size ();
        }
        result.append(subject, done, subject.max_size());
        return result;
}

测试.cc

#include <iostream>

template < class T >
T replace_all(
        T const &search,
        T const &replace,
        T const &subject
);

// #include "replace_all.cc"

using namespace std;

int main()
{
        string const a = "foo bar fee boor foo barfoo b";
        cout << replace_all<string>("foo", "damn", a) << endl;
        return 0;
}

当我尝试使用 gcc 4.1.2 编译它时

g++ -W -Wall -c replace_all.cc  
g++ -W -Wall -c test.cc  
g++ test.o replace_all.o  

我得到:

test.o: In function `main':
test.cc:(.text+0x13b): undefined reference to `
   std::basic_string<char, std::char_traits<char>, std::allocator<char> >
   replace_all< std::basic_string<char, std::char_traits<char>, std::allocator<char> > >(
       std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&,
       std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&,
       std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&
   )
'
collect2: ld returned 1 exit status

但是当我在 test.cc 中取消注释 #include "replace_all.cc" 并以这种方式编译时:

g++ -W -Wall test.cc

程序链接并产生预期的输出:

damn bar fee boor damn bardamn b

为什么链接失败,我该怎么做才能使其正常工作?

最佳答案

您不能链接模板,因为在有人尝试使用(实例化)模板之前,编译器不知道要生成哪些代码。

如果您知道要使用哪些类型或者知道它们是有限的,您可以“要求”编译器实例化模板。
如果您愿意 - 将其放入您的 .cc 文件:

template std::string replace_all( std::string const& search,
                                  std::string const& replace,
                                  std::string const& subject );


template glibmm::ustring replace_all( glibmm::ustring const& search,
                                      glibmm::ustring const& replace,
                                      glibmm::ustring const& subject );

关于c++ - 与字符串一起使用时对函数模板的 undefined reference (GCC),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/614233/

相关文章:

c++ - 从文本文件中读取行数并将它们存储为数组大小的常量 int c++

c++ - 为什么要尝试调用默认构造函数?

c++ - 在 C++ 中查询运行时多态性

javascript - javascript 中的字符串

C++ 静态结构模板方法返回枚举类型

c++ - 是否可以创建模板类的 vector 并调用其函数?

c++ - 如何初始化 static const char* enum type traits 数组?

string - 为什么我不能将 const(char)* 连接到 D 中的字符串?

string - 在某个字符后从字符串数组中删除所有内容

c++ - 为什么编译器不给出不明确的引用错误?