关于模板函数显示实例化的问题
定义了一系列模板函数,但是发现对于一些内部类型的实参调用,编译器并没用进行模板的隐式实例化。不知道为什么?请高人讲解!
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);
}
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);
}
}
}
int main(void *arg)
{
trace(100);//在这里编译器应该根据模板,隐式实例化函数trace(int, bool)
trace(100.001f);//在这里应该隐私和实例化函数trace(float, bool)
}
c c++ 模板 实例化
//以上代码省略,同上。。。
template void trace<int>(int, bool);
template void trace<float>(float, bool);