简体   繁体   中英

How to enable warnings on conversion from int to int64_t in gcc or clang

Is it possible to enable warnings in g++ or clang on cast from int to int64_t? Example:

int n;
cin >> n;
int64_t power = (1 << n);

I want that compiler tells me about this conversion in third line.

You could build something on these lines:

struct my_int64
{
    template<class Y> my_int64(const Y&)
    {
        static_assert(false, "can't do this");
    }
    template<> my_int64(const long long&) = default;
    /*ToDo - you need to hold the data member here, and 
      supply necessary conversion operators*/
};

Then

int n = 3;
my_int64 power = (1LL << n);

compiles, but

my_int64 power = (1 << n);

will not. In that sense, this is a good starting point. You could hack the preprocessor to use this in place of int64_t .

If you wanted a warning rather than an error, you could replace the static_assert with

my_int64 x{}; Y y = x; and hope the compiler emits a warning for a narrowing conversion, and trust it to optimise out the two statements as they are collectively a no-op.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM