假设我们有一个全局对象 pi,我们想根据上下文将其隐式转换为 float 或 double。以下不起作用:
#include <cmath>
class Pi {
public:
Pi() {}
operator float() const {
return std::atan(1.0f)*4.0f;
}
operator double() const {
return std::atan(1.0)*4.0;
}
};
const Pi pi;
#include <iostream>
#include <iomanip>
int main() {
std::cout << std::setprecision(50) << pi * 1.0f << std::endl;
std::cout << std::setprecision(50) << pi * 1.0 << std::endl;
}
它不起作用的原因是编译器不知道它是否应该将 pi 隐式转换为 float 或 double .但是,假设我们总是希望它在二元算术运算符中转换为另一个操作数的类型。在 C++11 或更高版本中是否有一些优雅的方法来实现它,或者我应该重载所有算术运算符?类似的东西:
class Pi {
public:
Pi() {}
float operator*(float x) const {
return (std::atan(1.0f)*4.0f) * x;
}
double operator*(double x) const {
return (std::atan(1.0)*4.0) * x;
}
//...
};
或者您能否想出一个更优雅的解决方案,将全局对象隐式转换为适合上下文的类型?
最佳答案
您的第一次尝试很接近。让我们在类外添加一个模板化的 * 运算符:
template<typename T>
T operator*(const Pi& pi, T&& other)
{
return static_cast<T>(pi) * std::forward<T>(other);
}
现在可以了。 Live Demo
#include <cmath>
#include <iostream>
#include <iomanip>
class Pi {
public:
Pi() {}
operator float() const {
return std::atan(1.0f)*4.0f;
}
operator double() const {
return std::atan(1.0)*4.0;
}
};
const Pi pi;
template<typename T>
T operator*(const Pi& pi, T&& other)
{
return static_cast<T>(pi) * std::forward<T>(other);
}
int main() {
std::cout << std::setprecision(50) << pi * 1.0f << std::endl;
std::cout << std::setprecision(50) << pi * 1.0 << std::endl;
}
输出:
3.1415927410125732421875
3.141592653589793115997963468544185161590576171875
如果您想真正严格地了解 T 的替代品,请查看 type_traits 内的 std::enable_if 和 std::is_floating_point
关于c++ - 在用它执行算术时隐式地将对象转换为浮点类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30937434/
我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,
我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass
我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h
我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]
这道题是thisquestion的逆题.给定一个散列,每个键都有一个数组,例如{[:a,:b,:c]=>1,[:a,:b,:d]=>2,[:a,:e]=>3,[:f]=>4,}将其转换为嵌套哈希的最佳方法是什么{:a=>{:b=>{:c=>1,:d=>2},:e=>3,},:f=>4,} 最佳答案 这是一个迭代的解决方案,递归的解决方案留给读者作为练习:defconvert(h={})ret={}h.eachdo|k,v|node=retk[0..-2].each{|x|node[x]||={};node=node[x]}node[
我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server
我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串
我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)
我遵循了教程http://gettingstartedwithchef.com/,第1章。我的运行list是"run_list":["recipe[apt]","recipe[phpap]"]我的phpapRecipe默认Recipeinclude_recipe"apache2"include_recipe"build-essential"include_recipe"openssl"include_recipe"mysql::client"include_recipe"mysql::server"include_recipe"php"include_recipe"php::modul
有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳