强制缩小转换警告

时间:2016-10-12 21:11:42

标签: 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成员的正文,以便触发编译器警告以缩小转换?我的目标是让用户意识到他们的代码可能存在问题。

3 个答案:

答案 0 :(得分:5)

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

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.

答案 1 :(得分:3)

要在缩小的通话中停止编辑,您可以在

上使用SFINAE
template <class U>
constexpr wrapper(wrapper<U> other)
: _data(other._data) 
{}

并将其更改为

template <class U, typename std::enable_if<sizeof(T) >= sizeof(U)>::type* = nullptr>
constexpr wrapper(wrapper<U> other)
: _data(other._data) 
{}

Live Example

如果要复制的基础类型的大小大于要初始化的对象的基础类型,则会停止编译。

答案 2 :(得分:0)

我推荐一种不同的方式。你不需要捣乱你的代码。使用g ++编译时,添加-Wconversion标志。

相关问题