我需要在C++編寫一個模板函數replace_all
這將需要一個字符串,wstring的,glibmm :: ustring等並用replace
取代的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;
}
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
爲什麼連接失敗,我能做些什麼,使工作?