Search code examples
c++explicit

Static cast return type


While compiling i get a non-constant-expression cannot be narrowed from type 'int' to result_type. This error occurs at the highlighted place. How would i chance it to a static_cast(). I am having trouble figure out what i need to change.

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

      private:
        mt19937 generator;

    };

Solution

  • It is because you are using {} to initialize generator.And form the standard draft n4296: If a narrowing conversion is required to initialize any of the elements, the program is ill-formed. when using {}.

    Form the standard draft 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.


    An example:

    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        int a = {1.2};
        return 0;
    }
    

    It gives the error: error: narrowing conversion of '1.2e+0' from 'double' to 'int' inside { } [-Wnarrowing] int a = {1.2};


    To solve this problem:

    generator{seed} => generator(seed).