简体   繁体   English

算术运算是否无效?

[英]Arithmetic operation with a void?

I know that the following, if possible, would be an absolutely bad practice, but I want to know if this is possible. 我知道,如果可能的话,以下做法绝对是错误的做法,但我想知道是否可行。

The question is the following: is it possible in C++ (and in a way the compiler does not throw any warning), to perform a useless arithmetic operation with a function returning a void. 问题如下:在C ++中(以某种方式编译器不会引发任何警告),是否有可能执行无用的算术运算,而函数会返回一个void。

std::vector<int> v;
int i = 42 + v.resize(42); 
/* How to transform the last line to execute resize and to have i = 42 */

I know that this is stupid, but that is not the question... 我知道这很愚蠢,但这不是问题。

我不确定这是否有意义,但是您可以在此处使用逗号运算符

int i = (v.resize(42), 42);

You could use the comma operator : 您可以使用逗号运算符

int i = (v.resize(42), 42);

and with GCC you could use its statement expression extension: GCC中,您可以使用其语句表达式扩展名:

int i = ({v.resize(42); 42;})

and in standard C++11 you could use and call an anonymous closure : 在标准C ++ 11中,您可以使用并调用匿名闭包

int i = ([&v]() {v.resize(42); return 42;}());

Type void has no values so it may not be used in arithmetic expressions. 类型void没有值,因此可能无法在算术表达式中使用。

In my opinion the design of member function resize is bad. 我认为成员函数resize的设计不好。 Instead of void it should return the object itself. 它应该返回对象本身,而不是void In this case you could write for example 在这种情况下,您可以写例如

int i = v.resize(42).size(); 

I pointed out about this in the forum where the C++ Standard is discussed. 我在讨论C ++标准的论坛中指出了这一点。

As for your question then you can write 至于你的问题,你可以写

int i = ( v.resize(42), v.size() );

using the comma operator. 使用逗号运算符。

Or maybe it would be better to separate these two calls 或者将这两个电话分开可能会更好

v.resize(42);
int i = v.size();

Don't see the point, but here's another way 看不到重点,但这是另一种方式

std::tie(i, std::ignore) = std::make_tuple(42, (v.resize(42),1) );

Also you can do: 您也可以执行以下操作:

if ((i=42)) v.resize(42); 

And don't forget 别忘了

do { v.resize(42); } while (!(i=42)); 

And the favorite 和最喜欢的

(i=42) ? v.resize(42) : i;

Or (the only serious c++ in the post) 或(帖子中唯一的严重C ++

int i(0);
std::vector<int> v(i=42);

Come on, this has no end 来吧,这没有止境

..... .....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM