When I compile this in Visual Studio 2015 I get an error: error C2398: Element '1': conversion from 'double' to 'float' requires a narrowing conversion
vector<float> v {2.46, 2.58, 2.0, 2.25, 3.0 };
But this works
vector<float> v{ (float)2.46, (float)2.58, (float)2.0, (float)2.25, (float)3.0 };
Is there an elegant solution to this code so I don't have to case all my inputs to float?
Maybe tweaking initializer_list ?
shamelessly stealing the comment from igor-tandetnik:
vector<float> v {2.46f, 2.58f, 2.0f, 2.25f, 3.0f };
And then complementing it to make it an answer:
The literal 0.42 has the type double. To have a literal of type float you need the f suffix: 0.42f.
You can read more (well... it's not that much) about integer literals and floating point literals
Related
I have a fairly simple bit of code in OMNET++ that takes one parameter from the user and uses it to decide several others
network ExampleNetwork
{
parameters:
int k;
int variable = (k / 2);
...
}
This code will build correctly but when running gives the error message:
'Cannot evaluate parameter 'test'. Cannot cast 1 from type double to
integer (note: no implicit conversion from double to int)'
where '1' is the value of k/2.
It seems the way to fix this would be to explicitly cast the result of the expression to int but I cannot find any documentation that states how to do this in NED files.
Does anyone know how they are meant to be written?
I believe this was working on earlier versions of OMNET++. I'm now on version 5.4 on Ubuntu.
Sorry for answering with a simple "RTFM", but this is the most effective: https://omnetpp.org/doc/omnetpp/manual/#sec:ned-functions:category-conversion
Since OMNeT++ 5.3, double values are no longer converted to int implicitly.
Use the int function, like this: int variable = int(k / 2);
I am using boost multiprecision library floating point number. I need to map a gmp_float to an tanh and then take it as a double because value of tanh will be [0, 1). When I use convert_to<double>() I get compilation error as shown in the snippet bellow.
typedef boost::multiprecision::number<boost::multiprecision::gmp_float<4>> float_type;
float_type previous_v = agent->_velocity(i, j);
float_type sigmapped_v = boost::multiprecision::tanh(previous_v);
double sigmoid_velocity = sigmapped_v.convert_to<double>();
// expected primary-expression before ‘double’ ^^
double v_probable = abs(sigmoid_velocity);
However explicitly casting it to double (double)sigmapped_v works
Going out on a limb, you are probably in a template context and float_type is a depends on a template argument.
You need to give the compiler type hints here:
double sigmoid_velocity = sigmapped_v.template convert_to<double>();
// ^^
Without the disambiguation hint the compiler will parse < as operator<
See also Where and why do I have to put the "template" and "typename" keywords?
Would somebody please describe the following code ?
template<typename _Rep2, typename = typename
enable_if<is_convertible<_Rep2, rep>::value
&& (treat_as_floating_point<rep>::value
|| !treat_as_floating_point<_Rep2>::value)>::type>
constexpr explicit duration(const _Rep2& __rep)
: __r(static_cast<rep>(__rep)) { }
template<typename _Rep2, typename _Period2, typename = typename
enable_if<treat_as_floating_point<rep>::value
|| (ratio_divide<_Period2, period>::den == 1
&& !treat_as_floating_point<_Rep2>::value)>::type>
constexpr duration(const duration<_Rep2, _Period2>& __d)
: __r(duration_cast<duration>(__d).count()) { }
These are the gcc/libstdc++ implementation of the std::chrono::duration constructors. We can look at them one at a time:
template <typename _Rep2,
typename = typename enable_if
<
is_convertible<_Rep2, rep>::value &&
(treat_as_floating_point<rep>::value ||
!treat_as_floating_point<_Rep2>::value)
>::type>
constexpr
explicit
duration(const _Rep2& __rep)
: __r(static_cast<rep>(__rep))
{ }
Formatting helps readability. It doesn't really matter what the style is, as long as it has some. ;-)
This first constructor is constexpr and explicit, meaning if the inputs are compile-time constants, the constructed duration can be a compile-time constant, and the input won't implicitly convert to the duration.
The overall purpose of this constructor is to explicitly convert a scalar (or emulation of a scalar) into a chrono::duration.
The second typename in the template argument list is a constraint on _Rep2. It says:
_Rep2 must be implicitly convertible to rep (rep is the representation type of the duration), and
Either rep is a floating point type (or emulating a floating point type), or _Rep2 is not a floating point type (or emulation of one).
If these constraints are not met, this constructor literally does not exist. The effect of these constraints is that you can construct floating-point-based durations from floating-point and integral arguments, but integral-based durations must be constructed from integral arguments.
The rationale for this constraint is to prevent silently discarding the fractional part of floating-point arguments. For example:
minutes m{1.5}; // compile-time error
This will not compile because minutes is integral based, and the argument is floating point, and if it did compile, it would silently discard the .5 resulting in 1min.
Now for the second chrono::duration constructor:
template <typename _Rep2,
typename _Period2,
typename = typename enable_if
<
treat_as_floating_point<rep>::value ||
(ratio_divide<_Period2, period>::den == 1 &&
!treat_as_floating_point<_Rep2>::value)
>::type>
constexpr
duration(const duration<_Rep2, _Period2>& __d)
: __r(duration_cast<duration>(__d).count())
{ }
This constructor serves as a converting chrono::duration constructor. That is, it converts one unit into another (e.g. hours to minutes).
Again there is a constraint on the template arguments Rep2 and Period2. If these constraints are not met, the constructor does not exist. The constraints are:
rep is floating-point, or
_Period2 / period results in a ratio with a denominator of 1 and _Rep2 is an integral type (or emulation thereof).
The effect of this constraint is that if you have a floating-point duration, then any other duration (integral or floating-point-based) will implicitly convert to it.
However integral-based durations are much more picky. If you are converting to an integral-based duration, then the source duration can not be floating-point-based and the conversion from the source integral-based duration to the destination integral-based duration must be exact. That is, the conversion must not divide by any number except 1 (only multiply).
For example:
hours h = 30min; // will not compile
minutes m = 1h; // ok
The first example does not compile because it would require division by 60, resulting in h which is not equal to 30min. But the second example compiles because m will exactly equal 1h (it will hold 60min).
What you can take away from this:
Always let <chrono> do conversions for you. If you are multiplying or dividing by 60 or 1000 (or whatever) in your code, you are needlessly introducing the possibility of errors. Furthermore <chrono> will let you know if you have any lossy conversions if you delegate all of your conversions to <chrono>.
Use implicit <chrono> conversions as much as possible. They will either compile and be exact, or they won't compile. If they don't compile, that means you are asking for a conversion that involves truncation error. It is ok to ask for truncation error, as long as you don't do so accidentally. The syntax for asking for a truncating conversion is:
hours h = duration_cast<hours>(30min); // ok, h == 0h
#include <stdint.h>
enum state : uint8_t {
NONE,
USA,
CAN,
MEX
};
struct X {
state st : 2; // compiles with uint8_t st : 2
};
Clang 3.9.0 compiles successfully.
GCC 4.8.4 and 5.3.0 complain with:
warning: ‘X::st’ is too small to hold all values of ‘enum state’
Who is right?
TL;DR
Both are correct.
The value of an enumeration is limited by the underlying type, not by the enumerators!
C++14, 7.2 Enumeration declarations, paragraph 8:
It is possible to define an enumeration that has values not defined by any of its enumerators.
Which means it is possible to:
state x = static_cast< state >(5);
That is what GCC is warning you about: enum state could have values that do not fit into 2 bits.
However, as long as you don't try to actually do that to X::st, everything is shiny.
That's (probably) why Clang is not warning you about it.
Since the standard does not demand a diagnostic either way, there's nothing wrong about warning, or not warning you.
I'm porting a game to OS X, which uses operators overloading for __m128 type like:
__forceinline __m128 operator - ( __m128 a, __m128 b )
{
return _mm_sub_ps ( a, b );
}
__forceinline __m128 operator * ( __m128 a, __m128 b )
{
return _mm_mul_ps ( a, b );
}
And Apple GCC v4.2.1 gives me the following errors:
error: 'float vector
operator-(float vector, float
vector)' must have an argument of class or enumerated type
error: 'float vector
operator*(float vector, float
vector)' must have an argument of class or enumerated type
I have found a link, describing this kind of errors as a GCC bug, which was solved in v4.0...
And now I'm completely lost... Please help me deal with this issue...
i'm using g++ 4.6.1 and found same error message on a similar situation, it happens when both arguments are builtin types:
algo operator+(const char* a,double b);
algo operator+(double a,const char* b);
I understand it would be tricky to redefine +(int,int) because the compiler rely on that to do calculations, thouse calculations occour on compile time, not on runtime, so the code you provide is not available at compile time and Later at runtime the data is already calculated.
too bad we can't do this, it should be allowed for builtin types provided that types were diferent (wich is my case) and for that case the compiler has no default answer.
for the case +(int,int) i think it would never be allowed because of the above explained. unless compilers accept some sort of parameters to leave that calc's to runtime (and i didnt check that kind of parameters yet). I think similar thing is happening to floats.