c++ - 强制缩小转换警告

标签 c++ c++14 compiler-warnings implicit-conversion narrowing

考虑以下说明一些收缩转换的代码:

template <class T>
class wrapper 
{   
    template <class> friend class wrapper;
    public:
        constexpr wrapper(T value)
        : _data(value)
        {}
        template <class U>
        constexpr wrapper(wrapper<U> other)
        : _data(other._data) 
        {}
        wrapper& operator=(T value)
        {_data = value; return *this;}
        template <class U>
        wrapper& operator=(wrapper<U> other)
        {_data = other._data; return *this;}
    private:
        T _data;
};

int main(int argc, char* argv[]) 
{
    wrapper<unsigned char> wrapper1 = 5U;
    wrapper<unsigned char> wrapper2{5U};
    wrapper<unsigned char> wrapper3(5U);
    wrapper<unsigned int> wrapper4 = 5U;
    wrapper<unsigned int> wrapper5{5U};
    wrapper<unsigned int> wrapper6(5U);
    wrapper<unsigned char> wrapper7 = wrapper4;  // Narrowing
    wrapper<unsigned char> wrapper8{wrapper5};  // Narrowing
    wrapper<unsigned char> wrapper9(wrapper6);  // Narrowing
    wrapper7 = wrapper4;  // Narrowing
    wrapper8 = wrapper5;  // Narrowing
    wrapper9 = wrapper6;  // Narrowing
    return 0;
}

如何更改wrapper 成员的主体,使其触发收缩转换的编译器警告?我的目标是让用户意识到他们的代码可能存在问题。

最佳答案

您可以使用统一的初始化语法触发缩小转换警告:

class wrapper 
{   
    template <class> friend class wrapper;
    public:
        constexpr wrapper(T value)
        : _data{value}
        {}
        template <class U>
        constexpr wrapper(wrapper<U> other)
        : _data{other._data} // note the curly brackets here
        {}
        wrapper& operator=(T value)
        {_data = value; return *this;}
        template <class U>
        wrapper& operator=(wrapper<U> other)
        {_data = {other._data}; return *this;} // and here
    private:
        T _data;
};

wrapper<unsigned int> wrapper1 = 5U;
wrapper<unsigned char> wrapper2 = wrapper1;  // Narrowing
wrapper<unsigned char> wrapper3(wrapper1);  // Narrowing
wrapper<unsigned char> wrapper4{wrapper1};  // Narrowing
wrapper2 = wrapper1;  // Narrowing

最后四行中的任何一行 will produce a narrowing conversion warning in g++, and compilation errors from the narrowing conversions in clang.

关于c++ - 强制缩小转换警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40008429/

相关文章:

swift - 修复 Swift 3 中的警告 "C-style for Statement is deprecated"

c++ - 为什么我必须将 const 与 constexpr 一起用于静态类函数?

c++ - select 不等待 C++ 套接字中的超时值

c++ - std::thread 使用带有 ref arg 的 lambda 编译失败

c++ - 应用于三元时 decltype 的返回类型(?:) expression

c++ - 从通用函数/lambda 推导出函数参数

oracle - 我可以让 SQL*Plus 退出并在函数编译失败时出错吗?

c++ - 如何将 cv::Scalar 分配给 cv::Mat?

c++ - 新的第二个参数,C++

c++ - 临时禁用调试代码