[英]How to remove narrowing conversion from int to char inside initializer list without casting every argument?
Here's what i tried to do: (with comparison to std::vector<int>
)这是我尝试做的:(与std::vector<int>
)
char s = 4;
std::vector<int> i;
std::vector<char> c;
i.insert(i.end(),{s+1,s+2,s+3}); // no warnings
c.insert(c.end(),{s+1,s+2,s+3}); // narrowing conversions of {s+1,s+2,s+3} from ints to chars
I know i can cast, but that gets ugly quickly.我知道我可以施展,但这很快就会变得丑陋。 (especially with more arguments) (尤其是有更多的论点)
c.insert(c.end(),{(char)(s+1),(char)(s+2),(char)(s+3),(char)(s+4),(char)(s+5),(char)(s+6)});
Do we have to live with this?我们必须忍受这个吗? Or is there a better way?或者,还有更好的方法?
Narrowing conversion in an initializer_list
is a problem.在initializer_list
缩小转换是一个问题。 See the answers to warning: narrowing conversion C++11 .请参阅警告的答案:缩小转换 C++11 。
You can use a helper function to get around the problem.您可以使用辅助函数来解决该问题。
namespace MyApp
{
char next(char c, int n) { return c+n; }
}
and use it as并将其用作
c.insert(c.end(), {MyApp::next(s, 1), MyApp::next(s, 2), MyApp::next(s, 3)});
If your list is regular, you could use a loop instead like如果您的列表是常规列表,则可以使用循环代替
for (int i = 1; i <= 3; ++1)
{
c.insert(c.end(), s + i);
}
If it s not regular, you could build a std::initializer_list
, and then use insert
's range overload to insert into the vector like如果它不正常,您可以构建一个std::initializer_list
,然后使用insert
的范围重载插入到向量中,如
{
auto elems = {s+1,s+2,s+3};
c.insert(c.end(), elems.begin(), elems.end());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.