草庐IT

c++ - 如何在没有此运算符的情况下为类型实现默认运算符<<(ostream&, T)?

coder 2024-02-23 原文

std::to_string添加到 c++11,我开始实现 to_string而不是更传统的 operator<<(ostream&, T) .我需要将两者链接在一起,以便合并依赖 operator<<(ostream&, T) 的库.我希望能够表达如果 T 有 operator<<(ostream&, T) , 用它;否则,使用 std::to_string .我正在制作一个更有限的版本的原型(prototype),该版本支持 operator<<对于所有枚举类。

enum class MyEnum { A, B, C };

// plain version works
//std::ostream& operator<<(std::ostream& out, const MyEnum& t) {
//  return (out << to_string(t));
//}

// templated version not working
template<typename T, 
         typename std::enable_if<std::is_enum<T>::value>::type
>
std::ostream& operator<<(std::ostream& out, const T& t) {
  return (out << to_string(t));
}

编译器说 error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'MyEnum') cout << v << endl;

问题:

  1. 为什么编译器找不到模板函数?
  2. 有没有办法实现通用解决方案?

最佳答案

如果存在 std::to_string,以下将起作用接受类型为 const MyEnum 的参数(根据 clang-703.0.31,不存在)。

#include <iostream>
#include <type_traits>

enum class MyEnum { A, B, C };

template<typename T>
typename std::enable_if<std::is_enum<T>::value, std::ostream &>::type
operator<<(std::ostream& out, const T& t) {
    return (out << std::to_string(t));
}

int main() {
  MyEnum a;

  std::cout << a << std::endl;
}

根据docs , 有两种使用方式 std::enable_if ,其中之一是使函数的返回类型仅在T 时有效。是一个枚举类型(在你的例子中)。这就是这段代码所显示的。如果std::is_enum<T>::valuetrue , 然后 std::enable_if<std::is_enum<T>::value, std::ostream &>::type结果 std::ostream &否则没有定义(这会让编译器对你大喊大叫)。

你可以可能写类似my::to_string的东西这也会尝试转换为用户定义的字符串类型:

namespace my {

    template<typename T>
    typename std::enable_if<! std::is_void<T>{} && std::is_fundamental<T>{}, std::string>::type
    to_string(T t) {
        return std::to_string(t);
    }

    std::string to_string(std::nullptr_t) = delete;

    std::string to_string(MyEnum a) {
        return "This is an enum";
    }
}

然后,您可以使用 my::to_string而不是 std::to_string在你的operator<< :

return (out << my::to_string(t));

编辑使用my::to_string现在当它的参数是 void 时会导致编译错误或 std::nullptr_t .


为什么你的代码不起作用

查看 docs 中的示例:

// 2. the second template argument is only valid if T is an integral type:
template < class T,
       class = typename std::enable_if<std::is_integral<T>::value>::type>
bool is_even (T i) {return !bool(i%2);}

如你所见,第二个模板参数是用class = /* enable_if stuff */写的,但在您的代码中,您只需执行 template< typename T, /* enable_if stuff */ > .因此,如果您遵循文档,您将得到正确的结果——编译器会说找不到 std::to_string 的特化。接受了 enum作为参数。

关于c++ - 如何在没有此运算符的情况下为类型实现默认运算符<<(ostream&, T)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37908812/

有关c++ - 如何在没有此运算符的情况下为类型实现默认运算符<<(ostream&, T)?的更多相关文章

  1. ruby - 如何在 Ruby 中顺序创建 PI - 2

    出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

  2. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  3. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  4. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  5. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

  6. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  7. ruby - 难道Lua没有和Ruby的method_missing相媲美的东西吗? - 2

    我好像记得Lua有类似Ruby的method_missing的东西。还是我记错了? 最佳答案 表的metatable的__index和__newindex可以用于与Ruby的method_missing相同的效果。 关于ruby-难道Lua没有和Ruby的method_missing相媲美的东西吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/7732154/

  8. ruby-on-rails - 如何从 format.xml 中删除 <hash></hash> - 2

    我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为

  9. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  10. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

随机推荐