关于模板函数的匹配问题

耳朵最威风 2013-02-03 02:32:41

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


这意味着,假如这个模板函数要提供给别人使用,真对const stringstream* 和 stringstream* 我需要具体化两个模板函数。

template<>
void trace<const stringstream*>(const stringstream* obj, bool newline);//给const stringstream *使用
template<>
void trace<stringstream*>(stringstream* obj, bool newline);//给stringstream *使用

真心觉得好麻烦啊。有什么方法可以一个模板具体化搞定吗?
谢谢各位高人了!
...全文
193 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
lvjing_CSDN 2013-02-03
  • 打赏
  • 举报
回复
#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;
}
gcc 4.6.2运行结果: #1#2
ri_aje 2013-02-03
  • 打赏
  • 举报
回复
特化没办法,不过可以用重载。

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
话说回来,通常情况下,const 和 non-const 类型的实现方法也不一样。你的例子如果是这样的话,接口统一就没法实现,因为内部处理的逻辑不一样的话,还是要想办法分开的。
耳朵最威风 2013-02-03
  • 打赏
  • 举报
回复
引用 1 楼 ri_aje 的回复:
特化没办法,不过可以用重载。 C/C++ code?1234567template <typename T>typenamestd::enable_if<std::is_same<std::stringstream, typename std::remove_const<T>::type ……
谢谢你的讲解!

65,187

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧