function's returned value type is either an alias or boolean once

How would we obtain a function's returned value type is either an alias or boolean once in a call (preferably if possible without overload) ?
let's realize that function's illustration only:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct U {
    int v;
}

int& f( U& u, int t ) {
      if (u.v == t) return u.v ;  // ... 
      else return (bool)0 ;      // ???
}

int main(){
  U u{7};
  int b,c, t=9;

  if (c=f(u, t)) b=c;
}
Thank
Last edited on
I don't understand what your illustration is showing.

Are you trying to get a function to be able to return more than one different type?
Perhaps you want something akin to std::optional
https://en.cppreference.com/w/cpp/utility/optional
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <string>
#include <functional>
#include <iostream>
#include <optional>
 
// optional can be used as the return type of a factory that may fail
std::optional<std::string> create(bool b) {
    if (b)
        return "Godzilla";
    return {};
}
 
// std::nullopt can be used to create any (empty) std::optional
auto create2(bool b) {
    return b ? std::optional<std::string>{"Godzilla"} : std::nullopt;
}
 
// std::reference_wrapper may be used to return a reference
auto create_ref(bool b) {
    static std::string value = "Godzilla";
    return b ? std::optional<std::reference_wrapper<std::string>>{value}
             : std::nullopt;
}
 
int main()
{
    std::cout << "create(false) returned "
              << create(false).value_or("empty") << '\n';
 
    // optional-returning factory functions are usable as conditions of while and if
    if (auto str = create2(true)) {
        std::cout << "create2(true) returned " << *str << '\n';
    }
 
    if (auto str = create_ref(true)) {
        // using get() to access the reference_wrapper's value
        std::cout << "create_ref(true) returned " << str->get() << '\n';
        str->get() = "Mothra";
        std::cout << "modifying it changed it to " << str->get() << '\n';
    }
}


There are other patterns to return a value while also determining the success of the operation itself, e.g. I see this often:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Example program
#include <iostream>

bool do_a_thing(int input, int& result)
{
    if (input == 42)
    {
        result = 0;
        return false;
    }
    else
    {
        result = input + 1;
        return true;
    }
}

int main()
{
    int result;
    if (do_a_thing(-1, result))
    {
        std::cout << "Success: " << result << '\n';   
    }
    else
    {
        std::cout << "Failure" << '\n'; // result is not valid.
    }
}

Where a parameter is passed by reference so that the function can set the result to that value, while returning a value to indicate success.
Last edited on
Topic archived. No new replies allowed.