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

li9yvcax  于 5个月前  发布在  C#
关注(0)|答案(2)|浏览(86)

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

示例

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

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

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

我现在在做什么:

float temperature;
float discard;

readValues(temperature, discard, discard, discard, discard);

我尝试的:

float temperature;
readValeus(temperature, null_ptr, null_ptr, null_ptr, null_ptr);
float temperature;
readValues(temperature, 0, 0, 0, 0);

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

5us2dqdw

5us2dqdw1#

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

(1)函数重载

void readValues(float& temperature, float& humidity, float& dewpoint);
void readValues(float& temperature, float& humidity);

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

(2)指针和默认参数

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

(3)避免输出参数

这是我个人的最爱。

struct Weather {
    float temperature;
    float humidity;
    float dewpoint;
};

Weather readValues();

// ...
Weather w = readValues();
auto [t, h, d] = readValues();
auto [t, h, _] = readValues();

(4)[[maybe_unused]]

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

float t, h;
[[maybe_unused]] float _;
readValues(t, h, _);


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

v1l68za4

v1l68za42#

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

void readValues(float& temperature, float& humidity, float& dewpoint, float& tempTrend, int& counter) {
    // Some operation to retrieve values
}

class t_Discarder final
{
    public: template<typename x_Object>
    /* IMPLICIT */ operator x_Object &(void) const
    {
        static x_Object s_object{};
        return s_object;
    }
};

t_Discarder _{};

int main()
{
    float temperature{};
    readValues(temperature, _, _, _, _);
}

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

相关问题