我辈岂是蓬蒿人!

C++ && keyWordSpotting

  C++博客 :: 首页 :: 联系 :: 聚合  :: 管理
  11 Posts :: 0 Stories :: 4 Comments :: 0 Trackbacks

常用链接

留言簿(9)

我参与的团队

搜索

  •  

积分与排名

  • 积分 - 6692
  • 排名 - 1379

最新评论

阅读排行榜

评论排行榜

       初学函数模版,一个“ bug” 让俺郁闷了一番,想了一个小时都没有想出所以然。虽求助于网络,发贴于 vckbase

       问题已经解决,帖子摘要如下:

      : 函数模版问题,为什么不能采用多文件方式。 
      : 郭晨 ( 书童)
所属论坛: C++ 论坛
本帖分数: 0
回复次数: 4
发表时间: 2006-8-12 19:09:50
正文内容:
1

#include <fstream>
#include <iostream>
using namespace std;
template<class Type >
Type min(Type a, Type b)
{
    return a < b ? a : b;
}

int main(int argc, char* argv[])
{
    cout << min(10, 20) << endl;
    return 0;
}

可以编译成功,运行得到正确结果。

2
)多文件方式

///////////////////////main.cxx
#include "min.h"
#include <fstream>
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
    cout << min(10, 20) << endl;
    return 0;
}
///////////////////////min.h
#ifndef _MIN_GHH_
#define _MIN_GHH_  1

template<class Type >
Type min(Type a, Type b);

#endif

//////////////////////min.cxx
#include "min.h"

template<class Type >
Type min(Type a, Type b)
{
    return a < b ? a : b;
}

编译报告错误:
Linking...
20060812_function_template.obj : error LNK2001: unresolved external symbol "int __cdecl min(int,int)" (?min@@YAHHH@Z)
Debug/20060812_function_template.exe : fatal error LNK1120: 1 unresolved externals
Error executing link.exe.

20060812_function_template.exe - 2 error(s), 0 warning(s)

////////////////////////////////////
问题:为什么会出现这种问题,如何解决?盼赐教。
最新修改:2006-8-12 19:41:10

 

回复人: newgun ( 书童

2006-8-12 19:34:29 ( 得分: 10

Re: 函数模版问题,为什么不能采用多文件方式。
c++标准中规定可以采用分离的编译模式,只需要通过在模板定义中的关键字template 之前加上关键字export 来声明一个可导出的函数模板当函数模板,被导出时我们就可以在任意程序文本文件中使用模板的实例如:
  // model2.h
//
分离模式: 只提供模板声明
template <typename Type> Type min( Type t1, Type t2 );
// model2.C
// the template definition
export template <typename Type>    //export
关键字
Type min( Type t1, Type t2 ) { /* ...*/ }

    
但是好像现在的好多编译器如vc7都还不支持这种结构,所以最好把模板的声明
和定义都放在头文件里

     

       感受:得到网友提示,真有一种“柳暗花明又一村”之感,这个所谓 bug 是这么简单又是这么不简单!

       一直认为应该是自己的错误,但没想到是编译器和标准兼容性的问题。看来自己的思维习惯应该有所改变了。应该多角度分析问题,而不能一味的想当然。

       Ps :自己也应该考虑尝试一个新的 C++ 编译器了,老用 vc ,感觉学的标准 C++ 都不纯,就象这次事件一样。

posted on 2006-08-12 20:32 keyws 阅读(556) 评论(1)  编辑 收藏 引用 所属分类: 程序调试

Feedback

# 关于模板的分离编译的实现 2008-12-22 08:09 云川
其实借助于现有的编译器模板是可以采用分离编译的方法的,只不过需要一些技巧。常用的方法是将在头文件的“×××.h”的末尾,include"×××.cpp"并确保文件编译且仅编译一次。比如:
///////////////////////main.cpp
#include "min.h"
#include <fstream>
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
cout << min(10, 20) << endl;
return 0;
}
///////////////////////min.h
#pragma once

template<class Type >
Type min(Type a, Type b);

include"min.cpp"

//////////////////////min.cpp
#ifndef MIN_CPP
#define MIN_CPP

#include "min.h"

template<class Type >
Type min(Type a, Type b)
{
return a < b ? a : b;
}

#endif  回复  更多评论
  


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理