【问题标题】:How to enable warnings on conversion from int to int64_t in gcc or clang如何在 gcc 或 clang 中启用从 int 到 int64_t 转换的警告
【发布时间】:2016-05-13 15:48:45
【问题描述】:

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

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

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

【问题讨论】:

  • 为什么你不想在上播时发出警告?
  • 第三个语句在语法上无效,请您更正一下吗?
  • 我假设您想要警告,因为 (1LL &lt;&lt; n) 是您真正想要的。
  • @NathanOliver,寻找 Loki Astari 的评论。这是一个常见的错误。当你写int64_t memory_size = 2 * 1024 * 1024 * 1024; 之类的东西并溢出时。但在这种情况下,它会给你一个警告,但在那种情况下,在帖子中 - 没有警告。
  • 因为它在很多地方都会自动发生,这样的警告标志会产生很多噪音。所以我认为它在一般情况下没有用。所以我不相信有一个(我确实尝试过谷歌,但没有发现任何有用的东西)。我想你可以创建自己的类来捕捉它。

标签: c++ g++ clang


【解决方案1】:

你可以在这些方面构建一些东西:

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;hope 编译器会针对 narrowing 转换发出警告,并相信它会优化这两个语句,因为它们共同是无操作的。

【讨论】:

  • 是的,我喜欢这个主意。但可能 static_assert 不是我要找的,因为我只想警告。
  • @SukhanovNiсkolay “因为我只想警告” 伙计,你很挑剔。恐怕您需要将static_assert() 重写为static_assertion_warn() 之类的东西,这只会导致编译器警告。玩得开心。
  • 好的。这是一个星期五。为此粘贴了一个想法。
  • @SukhanovNiсkolay 这里有一些more info ...很容易找到:-P ...
猜你喜欢
  • 1970-01-01
  • 2021-08-14
  • 1970-01-01
  • 1970-01-01
  • 2019-06-28
  • 2011-09-27
  • 2020-01-04
  • 2020-09-23
  • 2013-05-18
相关资源
最近更新 更多