首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >LNK2005模板函数

LNK2005模板函数
EN

Stack Overflow用户
提问于 2015-03-18 01:01:07
回答 1查看 1K关注 0票数 0

我首先在与main()相同的.cpp文件中实现以下函数。一切都运行得很完美。但是当我试图在一个头文件中定义它们并在一个单独的.cpp文件中实现它们时,我遇到了一些问题。

以下是我的原始代码:

代码语言:javascript
复制
template <class T> //implement the sum function of one single container
double sum(const T& source){...}

//explicit specialization for map
template<>
double sum<map<string, double>>(const map<string,double>& source){...}

template <class T> //implement the sum function for two iterators
double sum( const class T::const_iterator& start,  const class T::const_iterator& end){...}

//explicit specialization for map (sum function of iterator)
template<>
double sum<map<string, double>>(const map<string, double>::const_iterator& start,const map<string, double>::const_iterator& end){...}

void main(){...}

然后删除函数的实现,并在头文件中定义它们:

代码语言:javascript
复制
template <class T> //implement the sum function of one single container
double sum(const T& source);

//explicit specialization for map
template<>
double sum<map<string, double>>(const map<string,double>& source);

template <class T> //implement the sum function for two iterators
double sum( const class T::const_iterator& start,  const class T::const_iterator& end);

//explicit specialization for map (sum function of iterator)
template<>
double sum<map<string, double>>(const map<string, double>::const_iterator& start,const map<string, double>::const_iterator& end);

并在.cpp文件中实现它们。

然后,当我同时包含头文件和cpp文件,并运行项目时:

代码语言:javascript
复制
main(){...}

我收到如下错误消息:

代码语言:javascript
复制
sum.obj : error LNK2005: "double __cdecl sum<class std::map<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >....

谁能给我一个提示,我可能做错了什么?

非常感谢!

EN

回答 1

Stack Overflow用户

发布于 2015-03-18 01:04:11

我想这就是你的问题:

代码语言:javascript
复制
double sum<map<string, double>> # <-- here

看起来您使用的是">>“运算符,您应该留出空间来避免这种情况

代码语言:javascript
复制
double sum< map<string, double> > # space
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29105245

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档