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

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

本文关键字:int64 警告 转换 int gcc clang 启用      更新时间:2023-10-16

是否可以在从int到int64_t的强制转换中启用g++或clang中的警告?示例:

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

我希望编译器在第三行告诉我这个转换。

您可以在这些行上构建一些东西:

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*/
};

然后

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

编译,但

my_int64 power = (1 << n);

不会。从这个意义上说,这是一个很好的起点。你可以破解预处理器,用它来代替int64_t

如果你想要一个警告而不是错误,你可以用代替static_assert

my_int64 x{}; Y y = x;希望编译器发出缩小转换的警告,并相信它能优化这两个语句,因为它们共同是no-op。