简体   繁体   English

如何在gcc或clang中启用从int到int64_t转换的警告

[英]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? 是否可以在从int到int64_t的强制转换的g ++或clang中启用警告? 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 . 您可以破解预处理器以使用它代替int64_t

If you wanted a warning rather than an error, you could replace the static_assert with 如果您想要警告而不是错误,则可以将static_assert替换为

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. 希望编译器发出警告以缩小转换范围,并希望它可以优化这两个语句,因为它们共同是空操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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