C++ 如何禁止在C和C++;?

C++ 如何禁止在C和C++;?,c++,c++11,C++,C++11,有一个简单的程序: #include <iostream> int main() { int i = 1; double x = 2.5; x =i; // I do not want this can be compiled with no warning // I want only x=(double)i, or x=std::static_cast<double>i, that can compiled with no warnin

有一个简单的程序:

#include <iostream>
int main()
{
    int i = 1;
    double x = 2.5;
    x =i; // I do not want this can be compiled with no warning
    // I want only x=(double)i, or x=std::static_cast<double>i, that can compiled with no warning.
    std::cout << "x = " << x << std::endl;
    return 0;
}

我可以配置什么来实现严格的类型转换检查吗

我在C++11中工作,也很欣赏C解决方案


谢谢您的时间。

我相信您正在寻找这些警告标志:

-Wconversion -瓦利斯转换

-Warith-conversion

    Do warn about implicit conversions from arithmetic operations even when conversion of the operands to the same type cannot change their values. This affects warnings from -Wconversion, -Wfloat-conversion, and -Wsign-conversion.

    void f (char c, int i)
    {
      c = c + i; // warns with -Wconversion
      c = c + 1; // only warns with -Warith-conversion
    }

编辑:

如果这对你来说还不够,那么你可能会遇到一堵墙

但也有可能的替代方案

有一个核心指南,涵盖缩小转换问题

虽然coreguidelines通常不在编译器的范围内,但其他静态分析器工具可能适合您

叮当声:

Cpp核心检查:


如果这些都不是解决方案,那么你将把它看作是C++所规定的完全合法的转换。因为我所描述/链接的一切都是为了缩小转换范围。如果您的代码不会导致转换范围缩小,那么我认为目前没有任何工具能够捕捉到这一点(据我所知)。因为它是完全合法的C++。< /P>这不能在C++中完成,它不能这样工作。你最好的办法是一个自定义的CLAN-TY检查。此警告不是您可能在编译器中找到的供所有人使用的警告。它是所有转换,还是只是可能改变值的转换?gcc有

-Wconversion
(见文档:)。您可以使用
-Werror=conversion
将警告转换为硬错误。这不适用于
int
->
double
,因为这总是无损的,但它可能对其他情况有所帮助。你完全可以做你想做的事。。。有一节课。这就是类存在的原因:因此您可以定义“类型”的确切“语义”!这是大多数人一生中只会犯一次的错误。我认为花费大量时间或精力让编译器为您捕获它是不值得的;任何解决方案都会导致代码更难编写和读取,包含bug的几率也相应提高。该死,我会继续研究它。我研究了更多。请参见编辑。但如果这不起作用,我不确定。
-Warith-conversion

    Do warn about implicit conversions from arithmetic operations even when conversion of the operands to the same type cannot change their values. This affects warnings from -Wconversion, -Wfloat-conversion, and -Wsign-conversion.

    void f (char c, int i)
    {
      c = c + i; // warns with -Wconversion
      c = c + 1; // only warns with -Warith-conversion
    }