简体   繁体   中英

Conditional passing of a default argument to a function (using the '?' operator)

There be a function declared as

CalculateTimeSilence(float SilenceThresholdOverride = -1.f);

Is there a way to call it, so that I can utilize the conditional '?' operator to either choose a value for SilenceThresholdOverride or leave it at the default value ?

Expressed as pseudo-code:

CalculateTimeSilence(bUseOverride ? OverrideValue : default);

, where 'default' would be replaced by the compiler, by the value the argument was defaulted to in it's declaration (-1.f in this instance). If there were such a way, it would remove the need to match the default value or to write an If-Else statement.

Thanks, Sebastian

When you are calling the function with out specifiying the parameter, then the default is added at the call site, so when you call

CalculateTimeSilence();

Then you are actually calling

CalculateTimeSilence(-1.f);

There is no default or similar mechanism to get the default argument, but you can do that "manually"

const float default_value = -1.f;

CalculateTimeSilence(float SilenceThresholdOverride = default_value);

and then you can call it as desired:

CalculateTimeSilence(bUseOverride ? OverrideValue : default_value);

However, while the conditional operator comes in handy sometimes, often it obfuscates code and makes it difficult to read. In this case I'd perhaps rather write

auto x = bUseOverride ? OverrideValue : default_value;
CalculateTimeSilence(x);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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