Issue 10576 - enforce/enforceEx overload for returntype
Summary: enforce/enforceEx overload for returntype
Status: NEW
Alias: None
Product: D
Classification: Unclassified
Component: phobos (show other issues)
Version: D2
Hardware: All All
: P4 enhancement
Assignee: No Owner
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2013-07-08 18:01 UTC by David
Modified: 2024-12-01 16:18 UTC (History)
1 user (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description David 2013-07-08 18:01:27 UTC
auto foo() { int invalid_value = 3; return 3; }
auto result = enforceEx!(Exception, 3)(foo());

Currently this code doesn't work as expected:
auto result = enforceEx!Exception(foo() != 3);

result would be a boolean instead of the result of 3. If there is an overload which would take either a value to compare to or even a delagate (alias fun?) this would make enforceEx much more useful.
Comment 1 Andrej Mitrovic 2013-07-08 18:09:20 UTC
What David means is he wants the ability to both return the value and throw if that value is invalid, however simply using (!value) as enforceEx currently does will not work properly with e.g. signed integers. For example:

-----
import std.exception;

int returnValid() { return 5; }
int returnInvalid() { return -1; }

void main()
{
    int x = enforceEx!Exception(returnValid());
    assert(x == 5);  // ok

    // this doesn't throw, but we want -1 to signal failure
    enforceEx!Exception(returnInvalid());

    // so as a workaround we use the check inline, however..
    int y = enforceEx!Exception(returnInvalid() != -1);

    // .. it is not useful for the return value since the value becomes a bool
    int z = enforceEx!Exception(returnValid() != -1);
    assert(z == 5);  // now this fails
}
-----
Comment 2 dlangBugzillaToGithub 2024-12-01 16:18:15 UTC
THIS ISSUE HAS BEEN MOVED TO GITHUB

https://github.com/dlang/phobos/issues/9990

DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB