什么是表达模板数字文字的最好方法? [英] What is the best way to express a templated numeric literal?

查看:142
本文介绍了什么是表达模板数字文字的最好方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数可以减少到这样的:

  template< class T& 
T foo(T x)
{
return 123.45 / x;
}



我想确保数字文字1​​23.45与x 。让我们假设T可以是任何数字类型:signed / unsigned char to long-long或float to long-double。



123.45应该是T类型



我的要求




  • 不应发出警告(每打开一个警告)。

  • 我希望十进制数123.45在计算中使用的精度为T


  • 我想要达到这些目标的最优雅的解决方案。






    • 旧式铸造,即(T)123.45 在C ++中基本上已弃用。

    • static_cast< T>(123.45)

    • 我不确定是否有后缀(例如 123.45L )是必要的,以便在T long double 的情况下获得最大精度,或者编译器将自动使用最高精度的十进制到二进制转换。



    更新5-7-2014



    在我的代码库中将数百个转换改变为 T(123.45)后,我发现有时候这种语法不可用。例如,你不能做 long double(123.45),因为C ++不支持multitoken类型构造函数。在这些情况下,我选择了 static_cast< long double>(123.45)

    解决方案

    简单的

     模板< class T> 
    T foo(T x)
    {
    return T(123.45)/ x;
    }

    这将允许自定义数值类接受构造函数中的值。 p>

    I have a function that could be reduced to something like this:

    template<class T>
    T foo(T x)
    {
      return 123.45 / x;
    }
    

    I would like to ensure that the numeric literal 123.45 is the same type as x. Let's say that T could be any numeric type: signed/unsigned char to long-long or float to long-double.

    What is the most modern way to indicate that 123.45 should be of type T?

    My requirements

    • No warnings should be emitted (with every warning turned on).
    • I want the decimal number 123.45 to have the precision of T when used in the calculation.
    • I want the most elegant solution that achieves these goals.

    Issues under consideration

    • The “old-style cast”, i.e. (T)123.45 is essentially deprecated in C++.
    • static_cast<T>(123.45) seems like the right type of cast. However, it is verbose, and I have never seen this used on a literal.
    • I am unsure if a suffix (e.g. 123.45L) is necessary in order to get the maximum precision in the case of T being long double, or if the compiler will automatically use the highest precision decimal-to-binary conversion.

    Update 5-7-2014

    After changing hundreds of casts in my codebase to the form T(123.45), I found that there are times when this syntax is unavailable. For example, you can not do long double(123.45) because C++ does not support multitoken type constructors. In these cases, I have opted for static_cast<long double>(123.45).

    解决方案

    What about a simple

    template<class T>
    T foo(T x)
    {
      return T(123.45) / x;
    }
    

    which will allow custom numeric classes to accept the value in a constructor.

    这篇关于什么是表达模板数字文字的最好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆