免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 4227 | 回复: 2
打印 上一主题 下一主题

[C++] operator<<模板类型推断的问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2014-01-05 16:55 |只看该作者 |倒序浏览
本帖最后由 freebirdlino 于 2014-01-05 16:57 编辑

有一个 empty_logger_t

  1. class empty_logger_t : public logger_base_t
  2. {
  3. private:
  4.     empty_logger_t(void) : logger_base_t(std::cout) {};
  5.    
  6. public:
  7.     static empty_logger_t& getLogger(void) {
  8.         static empty_logger_t *pSingleton = new empty_logger_t;
  9.         return *pSingleton;
  10.     };
  11.    
  12.     template< typename Outs >
  13.     empty_logger_t& operator<< (Outs &o) {
  14.         return *this;
  15.     };
  16.    
  17.     // 针对流操纵符的重载
  18.     empty_logger_t& operator<< (std::ostream& (*pf) (std::ostream&)) {
  19.         return *this;
  20.     };
  21. };
复制代码
我的问题是,为什么不加上针对流操纵符的重载,像下面的代码就编译不过?
  1. emptylog<<std::endl;
复制代码
SO 上的解释:http://stackoverflow.com/questio ... age/8416221#8416221
Your problem is not about the chain of << , a single log << endl would also cause the problem. It is because std::endl is a template function:


为什么 流操纵符是 个模板函数就会推断不出来呢?

论坛徽章:
5
技术图书徽章
日期:2013-08-18 12:36:48水瓶座
日期:2013-12-27 16:10:36金牛座
日期:2014-01-24 10:25:23金牛座
日期:2014-01-24 10:50:03巨蟹座
日期:2014-01-24 16:27:28
2 [报告]
发表于 2014-01-05 21:43 |只看该作者
It is because std::endl is a template function

It is because std::endl is a template function is not a certain function
  1. template<typename _CharT, typename _Traits>
  2. inline basic_ostream<_CharT, _Traits>& endl(basic_ostream<_CharT, _Traits>& __os){
  3.     return flush(__os.put(__os.widen('\n')));
  4. }
复制代码
当你用std::endl去推断Outs的类型,谁来推断_CharT和_Traits的类型?

论坛徽章:
0
3 [报告]
发表于 2014-01-07 22:11 |只看该作者
回复 2# math_cai


    感谢回复,确实是因为这样。
    但这也太坑了,因为像 std::hex 之类的是没问题的,直觉上应该 std::endl 也一样。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP