Let's take the following simple example:
#include <vector>
#include <cstdint>
using ::std::vector;
using ::std::uint64_t;
using ::std::uint32_t;
int main(int argc, char *argv[])
{
vector<uint64_t> v;
uint32_t i = 1;
v.push_back(i);
return 0;
}
When I compile it with:
g++ -std=c++11 -Wall -Wconversion -Wpedantic a.cpp
I don't get any conversion error. However, I want gcc to warn me because the types uint64_t
and uint32_t
don't perfectly match. I undertand that a uint32_t
fits into a uint64_t
, but it still some code smell to me. (I would like gcc to force me to cast it)
Is there a way to have gcc warn about that?
There is nothing wrong with that conversion because the a uint32_t
being converted to a uint64_t
will not alter the value: https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wconversion-499
#include <iostream>
#include <cstdint>
int main(int argc, char *argv[])
{
std::uint32_t i = 1;
std::uint64_t j = 1;
// warning: conversion to 'uint32_t {aka unsigned int}' from 'uint64_t {aka long long unsigned int}' may alter its value
// i = j;
// No problem here
j = i;
// Use j to avoid an error
std::cout << j << std::endl;
return 0;
}
There won't be a compiler flag for j = i;
because there is nothing wrong with it, the "smell" is just your preference
uint64_t
have 64 bits, uint32_t
have only 32 bits. When uint32
change into uint64
, it only add 0
in high 32 bits, the data is unchanged. So there is no any warning needed for a compiler. But when uint64_t
change into uint32_t
, the compiler would give a warning, because the data maybe be changed. So the warning you want could not get.
You can't do this, but with C++11 UDLs you can write your own set of classes to be used instead of the normal integers, so you can provide whatever semantics you want.
It's probably quite painful for integers, I have only done it for string literals.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.