首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

关于模板函数显示实例化的有关问题

2013-02-24 
关于模板函数显示实例化的问题定义了一系列模板函数,但是发现对于一些内部类型的实参调用,编译器并没用进

关于模板函数显示实例化的问题
定义了一系列模板函数,但是发现对于一些内部类型的实参调用,编译器并没用进行模板的隐式实例化。不知道为什么?请高人讲解!
test.h


namespace qjtest
{
template<typename T> 
void trace(T obj, bool newline = true);

template<>
void trace<stringstream*>(stringstream* obj, bool newline);

template<>
void trace<string*>(string* obj, bool newline);

template<>
void trace<char*>(char* obj, bool newline);
}


test.cpp

namespace qjtest
{
template<typename T> 
void trace(T obj, bool newline)
{
stringstream ss;
ss << obj;
trace(&ss, newline);
}

template<>
void trace<stringstream*>(stringstream* obj, bool newline)
{
if(obj)
{
trace(&obj->str(), newline);
}
}

template<>
void trace<string*>(string* obj, bool newline)
{
if(obj)
{
OutputDebugString(obj->c_str());
if(newline)
{
OutputDebugString(NEXT_LINE_END);
}
}
}

template<>
void trace<char*>(char* obj, bool newline)
{
if(obj)
{
const string s = string(obj);
trace(&s, newline);
}
}
}


main.cpp

int main(void *arg)
{
    trace(100);//在这里编译器应该根据模板,隐式实例化函数trace(int, bool)
    trace(100.001f);//在这里应该隐私和实例化函数trace(float, bool)
}


生成程序的时候抛出一下链接错误。。。

1>正在链接...
1>demo7_5.obj : error LNK2019: 无法解析的外部符号 "void __cdecl qjtest::trace<float>(float,bool)" (??$trace@M@qjtest@@YAXM_N@Z),该符号在函数 "int __cdecl Game_Init(void *,int)" (?Game_Init@@YAHPAXH@Z) 中被引用
1>demo7_5.obj : error LNK2019: 无法解析的外部符号 "void __cdecl qjtest::trace<int>(int,bool)" (??$trace@H@qjtest@@YAXH_N@Z),该符号在函数 "int __cdecl Game_Init(void *,int)" (?Game_Init@@YAHPAXH@Z) 中被引用

然后我在test.h后面加了显示实例化后解决。而且输出也正常。
百思不得其解啊!!求高人解释!多谢!!
test.h

        //以上代码省略,同上。。。
        template void trace<int>(int, bool);
template void trace<float>(float, bool);
c c++ 模板 实例化
[解决办法]
编译器不支持template的分离模型,必须都放在头文件中
[解决办法]
只有支持export关键字的编译器才支持模板的分离编译。

热点排行