静态转换 return 类型

Static cast return type

编译时我得到一个非常量表达式不能从类型 'int' 缩小到 result_type。此错误发生在突出显示的位置。我怎么可能把它变成 static_cast()。我无法弄清楚我需要改变什么。

   class UniformRandom
    {
      public:
        **UniformRandom( int seed = currentTimeSeconds( ) ) : generator{ seed }**
        {
        }

      private:
        mt19937 generator;

    };

是因为你在使用{}初始化generator。并且在使用{}时形成标准稿n4296:If a narrowing conversion is required to initialize any of the elements, the program is ill-formed.

形成标准草案n4296:

A narrowing conversion is an implicit conversion

— from a floating-point type to an integer type, or

— from long double to double or float, or from double to float, except where the source is a constant expression and the actual value after conversion is within the range of values that can be represented (even if it cannot be represented exactly), or

— from an integer type or unscoped enumeration type to a floating-point type, except where the source is a constant expression and the actual value after conversion will fit into the target type and will produce the original value when converted back to the original type, or

— from an integer type or unscoped enumeration type to an integer type that cannot represent all the values of the original type, except where the source is a constant expression whose value after integral promotions will fit into the target type.


一个例子:

#include <iostream>

using namespace std;

int main()
{
    int a = {1.2};
    return 0;
}

它给出错误:error: narrowing conversion of '1.2e+0' from 'double' to 'int' inside { } [-Wnarrowing] int a = {1.2};


解决这个问题:

generator{seed} => generator(seed).