gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:02:30 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com