简体   繁体   English

C++返回类型nodiscard函数和void函数定义

[英]C++ return type nodiscard function and void function definition

If i have a version of a function that returns a boolean i want to have a version of the function that doesnt return a boolean.如果我有一个返回布尔值的函数版本,我想要一个不返回布尔值的函数版本。 i tried nodiscard around the function definition but it didnt allow for both definitions.我尝试在函数定义周围使用 nodiscard,但它不允许同时使用这两个定义。 are functions returning booleans the same speed as functions returning void?返回布尔值的函数与返回 void 的函数的速度是否相同? If not then is there a way to declare a void and a bool version of a function?如果没有,那么有没有办法声明一个函数的 void 和 bool 版本?

I dont need more space to describe my issue it is very simple.我不需要更多空间来描述我的问题,这很简单。 But i have to do weird things to allow me to post my question.但我必须做一些奇怪的事情才能让我发布我的问题。

are functions returning booleans the same speed as functions returning void?返回布尔值的函数与返回 void 的函数的速度是否相同?

The overhead of assigning a value to a bool , and discarding a bool return value, is infinitesimal to the point of not being noticeable.将值分配给bool并丢弃bool返回值的开销非常小,以至于不会引起注意。 So, essentially, yes for all practical purposes.所以,基本上,对于所有实际目的都是如此。

is there a way to declare a void and a bool version of a function?有没有办法声明一个函数的 void 和 bool 版本?

Functions can't be overloaded on return value alone.函数不能仅在返回值上重载。 You would have to either use separate function names:您必须使用单独的函数名称:

bool myFunctionWithResult()
{
    ...
    return ...;
}

void myFunctionWithoutResult()
{
    myFunctionWithResult();
}
void doSomething()
{
    bool result = myFunctionWithResult();
    // use result as needed...
}

void doSomethingElse()
{
    myFunctionWithoutResult();
}

Or else give one of them an output parameter:或者给其中之一一个输出参数:

void myFunction(bool &result)
{
    ...
    result = ...;
}

void myFunction()
{
    bool ignored;
    myFunction(ignored);
}
void doSomething()
{
    bool result;
    myFunction(result);
    // use result as needed...
}

void doSomethingElse()
{
    myFunction();
}

In which case, you could simplify that into a single function:在这种情况下,您可以将其简化为单个函数:

void myFunction(bool *result = nullptr)
{
    ...
    if (result)
        *result = ...;
}
void doSomething()
{
    bool result;
    myFunction(&result);
    // use result as needed...
}

void doSomethingElse()
{
    myFunction();
}

Needless to say, for a bool (or any other primitive type), this is needlessly complicated.不用说,对于bool (或任何其他原始类型),这是不必要的复杂。 Just return the bool /primitive normally, and let the caller discard the value if it wants to.只需正常return bool /primitive ,并让调用者根据需要丢弃该值。 This kind of micro-optimizing only really matters if the output is a more complex type, say a class with dynamically allocated members, where returning an instance actually invokes overhead that you may need to avoid at times.这种微优化只有在输出是更复杂的类型时才真正重要,例如具有动态分配成员的类,其中返回实例实际上会调用您有时可能需要避免的开销。

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

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