在C#中是否存在与变量discard '_'等效的C++?

li9yvcax  于 2024-01-09  发布在  C#
关注(0)|答案(2)|浏览(388)

在C#中,当想要显式忽略操作结果时,有一个方便的特性,使用下划线_作为丢弃变量。
我目前正在C++中寻找一个等效的功能或解决方法,允许我在从函数中检索多个值时丢弃特定值或保存内存分配。

示例

假设我有一个这样的函数:

  1. void readValues(float& temperature, float& humidity, float& dewpoint, float& tempTrend, float& humTrend) {
  2. // Some operation to retrieve values
  3. }

字符串
如果我只需要知道温度,而我没有一个特定于温度的函数,我如何以最有效的方式丢弃其他值?
或者任何其他方法可以帮助在Arduino/ESP 32环境中忽略函数的某些返回值时节省内存空间?

我现在在做什么:

  1. float temperature;
  2. float discard;
  3. readValues(temperature, discard, discard, discard, discard);

我尝试的:

  1. float temperature;
  2. readValeus(temperature, null_ptr, null_ptr, null_ptr, null_ptr);
  1. float temperature;
  2. readValues(temperature, 0, 0, 0, 0);

的字符串
感谢您的任何见解或建议!

5us2dqdw

5us2dqdw1#

有几种方法可以做你想做的事情。但是没有直接等价于discard关键字。
首先,在这种情况下,我不会担心内存效率,即使你总是返回所有值,未使用的值和它们的创建可能会被优化掉。
此外,输出参数在C++中通常是不受欢迎的。(参见F.20:对于“out”输出值,首选返回值而不是输出参数)您可以将东西打包到struct中,然后简单地使用您感兴趣的部分。无论如何,这里有一些可能的解决方案:

(1)函数重载

  1. void readValues(float& temperature, float& humidity, float& dewpoint);
  2. void readValues(float& temperature, float& humidity);

字符串
第二个重载使dewpoint有效地成为可选参数。

(2)指针和默认参数

  1. void readValues(float& temperature, float& humidity, float* dewpoint = nullptr);
  2. // ...
  3. readValues(t, h); // don't provide dewpoint
  4. readValues(t, h, &d); // provide dewpoint

(3)避免输出参数

这是我个人的最爱。

  1. struct Weather {
  2. float temperature;
  3. float humidity;
  4. float dewpoint;
  5. };
  6. Weather readValues();
  7. // ...
  8. Weather w = readValues();
  9. auto [t, h, d] = readValues();
  10. auto [t, h, _] = readValues();

(4)[[maybe_unused]]

  1. void readValues(float& temperature, float& humidity, float& dewpoint);
  2. // ...
  3. float t, h;
  4. [[maybe_unused]] float _;
  5. readValues(t, h, _);


您仍然需要提供一个额外的参数,但是[[maybe_unused]]清楚地表达了意图,并抑制了有关未使用变量的警告(如果有的话)。

展开查看全部
v1l68za4

v1l68za42#

实现某种_代理,提供对象来存储输出值,但不对它做任何事情,这是很简单的。

  1. void readValues(float& temperature, float& humidity, float& dewpoint, float& tempTrend, int& counter) {
  2. // Some operation to retrieve values
  3. }
  4. class t_Discarder final
  5. {
  6. public: template<typename x_Object>
  7. /* IMPLICIT */ operator x_Object &(void) const
  8. {
  9. static x_Object s_object{};
  10. return s_object;
  11. }
  12. };
  13. t_Discarder _{};
  14. int main()
  15. {
  16. float temperature{};
  17. readValues(temperature, _, _, _, _);
  18. }

字符串
online compiler
在生产代码中,最好提供正确命名的参数,并显式地将它们标记为未使用,或者发明一个更好的查询接口,不需要每次都提供这么多参数,其中大部分都被丢弃。

展开查看全部

相关问题