c – 与字符串(GCC)一起使用时对函数模板的未定义引用
发布时间:2020-12-16 10:38:19 所属栏目:百科 来源:网络整理
导读:我需要在C中编写一个模板化函数replace_all,它将接受一个字符串,wstring,glibmm :: ustring等,并用subject替换所有出现的搜索主题. replace_all.cc template class T T replace_all( T const search,T const replace,T const subject) { T result; typename
我需要在C中编写一个模板化函数replace_all,它将接受一个字符串,wstring,glibmm :: ustring等,并用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,subject.max_size()); return result; } test.cc #include <iostream> template < class T > T replace_all( T const &search,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::allocator<char> > >( std::basic_string<char,std::allocator<char> > const&,std::basic_string<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 为什么链接失败,我该怎么做才能使它工作? 解决方法
您无法链接模板,因为编译器在尝试使用(实例化)模板之前不知道要生成哪些代码.
如果您知道要使用哪种类型或者您知道它们是有限的,您可以“询问”编译器实例化模板. 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 ); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容