![](/img/trans.png)
[英]undefined reference to variable template of pointer to function in clang but not gcc
[英]Undefined reference to function template when used with string (GCC)
我需要在 C++ 中编写一个模板化的 function 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;
}
测试.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
程序链接并产生预期的 output:
damn bar fee boor damn bardamn b
为什么链接失败,我该怎么做才能使它工作?
您无法链接模板,因为编译器在有人尝试使用(实例化)模板之前不知道要生成哪些代码。
如果您知道要使用哪些类型或者您知道它们是有限的,您可以“要求”编译器实例化模板。
如果你愿意 - 把它放到 your.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 );
编译器需要在实例化点查看模板定义,否则无法生成专门为您实例化模板的类型的代码。 正确的方法是将模板函数的实现放在 header 文件中,或者像你一样 #include the.cc 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.