我需要在C ++中编写一个模板函数 replace_all ,它将接受一个字符串,wstring,glibmm :: ustring等,并替换所有出现的在中搜索中的 c
I need to write a templated function replace_all in C++ which will take a string, wstring, glibmm::ustring etc. and replace all occurrences of search in subject with replace.
replace_all.cc
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
When I try to compile this using 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但是当我取消注释 #includereplace_all.cc并编译这种方式:
But when I uncomment #include "replace_all.cc" in test.cc and compile this way:
g++ -W -Wall test.cc程序链接并产生预期输出:
The program links and produces expected output:
damn bar fee boor damn bardamn b为什么链接失败,我该怎么做使它工作?
Why linking fails and what can I do to make it work?
推荐答案模板作为编译器不知道在有人尝试使用(实例化)模板之前生成哪个代码。
You can't link templates as compiler don't know which code to generate before someone tries to use ( instantiate ) templates.
如果知道哪些类型您要使用,或者您知道他们有限。 如果您想要 - 将其放在您的.cc文件中:
You can "ask" compiler to instantiate template if you knows which types are you going to use or if you know that they are limited. If you want - put this to your .cc file:
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 );更多推荐
与字符串(GCC)一起使用时对函数模板的未定义引用
发布评论