代码之家  ›  专栏  ›  技术社区  ›  code_fodder

针对不同目标的c++强制转换(编译器)

  •  1
  • code_fodder  · 技术社区  · 6 年前

    鉴于以下情况:

    code-link

    #include <iostream>
    #include <vector>
    #include <stdint.h>
    
    using namespace std;
    
    int main()
    {
        cout<<"Hello World";
        std::vector<std::string> test_vect {"1", "2"};
        long unsigned int size = static_cast<long unsigned int>(test_vect.size());
    
        std::cout << "size: " << size << std::endl;
        return 0;
    }
    

    以及以下编译选项: g++ file.c -Wall -Wextra "-Werror" "-Wuseless-cast"

    你可以看到我正在演 vector.size() long unsigned int

    我知道这两个 unsigned long size_t

    所以,一个编译器抱怨我正在转换类型,所以我强制转换,但是另一个编译器抱怨无用的强制转换-所以我删除强制转换-然后我们继续:(

    我正要把 -Wuseless-cast

    2 回复  |  直到 6 年前
        1
  •  6
  •   Lightness Races in Orbit    6 年前

    我要做的是编写一些没有设置所有强制转换警告的代码(在交叉编译时这可能是optamistic)

    如果你有强制类型转换,交叉编译时会很乐观。

    没有石膏。使变量类型为 std::size_t .

    我正要把 -Wuseless-cast

    那是另一种选择。

        2
  •  2
  •   nada    6 年前

    作为 Lightness Races in Orbit 指出, size_t 是一个选项,它应该有一个适当的宏来让编译器高兴,如果您不想使用它-使您的变量 auto decltype(test_vect.size()) 将是另一种选择:

    auto size = test_vect.size();
    

    decltype(test_vect.size()) size = test_vect.size();
    
        3
  •  1
  •   Demosthenes    6 年前

    想到的一个论点是:为什么您的size变量需要 long unsigned 而不是 std::size_t ?

    万一有一个令人信服的理由,那(C++ 17):

    long unsigned size;
    if constexpr(sizeof(long unsigned)!=sizeof(std::size_t))
        size = static_cast<long unsigned>(...);
    else
        size = ...;