关于模板函数的匹配问题
template<typename T>
void trace(const T obj, bool newline = true);// #1
template<>
void trace<const stringstream*>(const stringstream* obj, bool newline);// #2
template<>
void trace<string*>(string* obj, bool newline);// #3
template<>
void trace<const char*>(const char* obj, bool newline);// #4
stringstream ss0;
ss0 << 100;
trace(&ss0);//我发现在这里匹配的是#2
const stringstream ss1;
ss1 << 100;
trace(&ss1);//我发现在这里匹配的是#1
template<>
void trace<const stringstream*>(const stringstream* obj, bool newline);//给const stringstream *使用
template<>
void trace<stringstream*>(stringstream* obj, bool newline);//给stringstream *使用
template <typename T>
typename
std::enable_if<std::is_same<std::stringstream,
typename std::remove_const<T>::type
>::value
>::type
trace (T*const, bool = true); // #2
#include <iostream>
#include <sstream>
#include <string>
template<typename T>
void trace(const T obj, bool newline = true)// #1
{
std::cout<< "#1";
}
template<>
void trace<const std::stringstream*>(const std::stringstream* obj, bool newline)
{
std::cout<< "#2";
}
template<>
void trace<std::string*>(std::string* obj, bool newline)
{
std::cout<< "#3";
}
template<>
void trace<const char*>(const char* obj, bool newline)
{
std::cout<< "#4";
}
int main()
{
std::stringstream ss0;
ss0 << 100;
trace(&ss0);
const std::stringstream ss1;
//ss1 << 100;
trace(&ss1);
return 0;
}
#1#2