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

时间:2016-05-13 15:48:46

标签: c++ g++ clang

是否可以在g ++或clang中启用从int到int64_t的警告? 例如:

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

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

1 个答案:

答案 0 :(得分:2)

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

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;希望编译器发出缩小转换的警告,并相信它可以优化这两个语句,因为它们统称为同前。