简体   繁体   English

如何在不强制转换每个参数的情况下在初始值设定项列表中删除从 int 到 char 的缩小转换?

[英]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.

相关问题 在 { } | 内缩小从 int 到 char 的转换 char 的签名问题 - Narrowing Conversion from int to char inside { } | An issue with signedness of char 错误:{}中的&#39;199&#39;从&#39;int&#39;到&#39;char&#39;的转换变窄 - error: narrowing conversion of ‘199’ from ‘int’ to ‘char’ inside { } [-Wnarrowing] 缩小从 int 到 unsigned char 的转换 - Narrowing conversion from int to unsigned char 交叉编译时,“在 {} 内缩小从 &#39;int&#39; 到 &#39;char&#39; 的转换”以获得合法值 - "Narrowing conversion from 'int' to 'char' inside { }" for legal values when cross compiling C ++-从“ int”到“ unsigned char”的无效缩小转换 - C++ - Invalid narrowing conversion from “int” to “unsigned char” 在{}中将&#39;65280&#39;从&#39;int&#39;转换为&#39;short int&#39; - Narrowing conversion of '65280' from 'int' to 'short int' inside { } 缩小从 char 到 double 的转换 - Narrowing conversion from char to double 在{}中将&#39;((((int)a)+ -1)&#39;从&#39;int&#39;转换为&#39;int16_t {aka short int}&#39; - Narrowing conversion of ‘(((int)a) + -1)’ from ‘int’ to ‘int16_t {aka short int}’ inside { } 在不缩小范围的情况下初始化初始化器列表中的联合成员 - Initializing union member in initializer list without narrowing 缩小从char到uint8_t的转换 - Narrowing conversion from char to uint8_t
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM