【发布时间】:2026-01-11 06:05:02
【问题描述】:
我需要在 C++ 中编写一个模板化函数replace_all,它将接受一个字符串、wstring、glibmm::ustring 等,并将所有出现在subject 中的search 替换为replace。
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;
}
test.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
为什么链接会失败,我该怎么做才能让它工作?
【问题讨论】:
标签: c++ string templates gcc stl