standard template for returning a value with a boolean result flag












6















As I am beginning to take advantage of the C++17 structured bindings and if operator init statements for more elegant function result reporting and checking, I started doing the following, if accordance with C++ Core Guideline F21:



std::pair<bool, int>Foo()
{
return {true, 42}; //true means that function complete with no error and that 42 is a good value
}

void main(void)
{
if (auto [Result, Value] = Foo(); Result)
{
//Do something with the return value here
}
}


Then, of course, I though that it would be nice to have a reusable template for such return types so that nobody has to duplicate bool portion of the pair:



template <typename T> using validated = std::pair<bool,T>;

validated<int> Foo()
{
return {true, 42};
}

void main(void)
{
if (auto [Result, Value] = Foo(); Result)
{
//Do something with the return value here
}
}


This works great for me, but now I am wondering if there is some sort of standard equivalent of this template so that I don't have to reinvent the wheel and define it myself. Seems like an arbitrary type value coupled with a validity flag would be a useful construct, but I could not find anything in standard library. Am I missing something?










share|improve this question



























    6















    As I am beginning to take advantage of the C++17 structured bindings and if operator init statements for more elegant function result reporting and checking, I started doing the following, if accordance with C++ Core Guideline F21:



    std::pair<bool, int>Foo()
    {
    return {true, 42}; //true means that function complete with no error and that 42 is a good value
    }

    void main(void)
    {
    if (auto [Result, Value] = Foo(); Result)
    {
    //Do something with the return value here
    }
    }


    Then, of course, I though that it would be nice to have a reusable template for such return types so that nobody has to duplicate bool portion of the pair:



    template <typename T> using validated = std::pair<bool,T>;

    validated<int> Foo()
    {
    return {true, 42};
    }

    void main(void)
    {
    if (auto [Result, Value] = Foo(); Result)
    {
    //Do something with the return value here
    }
    }


    This works great for me, but now I am wondering if there is some sort of standard equivalent of this template so that I don't have to reinvent the wheel and define it myself. Seems like an arbitrary type value coupled with a validity flag would be a useful construct, but I could not find anything in standard library. Am I missing something?










    share|improve this question

























      6












      6








      6








      As I am beginning to take advantage of the C++17 structured bindings and if operator init statements for more elegant function result reporting and checking, I started doing the following, if accordance with C++ Core Guideline F21:



      std::pair<bool, int>Foo()
      {
      return {true, 42}; //true means that function complete with no error and that 42 is a good value
      }

      void main(void)
      {
      if (auto [Result, Value] = Foo(); Result)
      {
      //Do something with the return value here
      }
      }


      Then, of course, I though that it would be nice to have a reusable template for such return types so that nobody has to duplicate bool portion of the pair:



      template <typename T> using validated = std::pair<bool,T>;

      validated<int> Foo()
      {
      return {true, 42};
      }

      void main(void)
      {
      if (auto [Result, Value] = Foo(); Result)
      {
      //Do something with the return value here
      }
      }


      This works great for me, but now I am wondering if there is some sort of standard equivalent of this template so that I don't have to reinvent the wheel and define it myself. Seems like an arbitrary type value coupled with a validity flag would be a useful construct, but I could not find anything in standard library. Am I missing something?










      share|improve this question














      As I am beginning to take advantage of the C++17 structured bindings and if operator init statements for more elegant function result reporting and checking, I started doing the following, if accordance with C++ Core Guideline F21:



      std::pair<bool, int>Foo()
      {
      return {true, 42}; //true means that function complete with no error and that 42 is a good value
      }

      void main(void)
      {
      if (auto [Result, Value] = Foo(); Result)
      {
      //Do something with the return value here
      }
      }


      Then, of course, I though that it would be nice to have a reusable template for such return types so that nobody has to duplicate bool portion of the pair:



      template <typename T> using validated = std::pair<bool,T>;

      validated<int> Foo()
      {
      return {true, 42};
      }

      void main(void)
      {
      if (auto [Result, Value] = Foo(); Result)
      {
      //Do something with the return value here
      }
      }


      This works great for me, but now I am wondering if there is some sort of standard equivalent of this template so that I don't have to reinvent the wheel and define it myself. Seems like an arbitrary type value coupled with a validity flag would be a useful construct, but I could not find anything in standard library. Am I missing something?







      c++ c++17 c++-standard-library






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 13 '18 at 14:44









      Regus PregusRegus Pregus

      334




      334
























          2 Answers
          2






          active

          oldest

          votes


















          9














          std::optional is exactly what you are asking about. It's even in the description:




          A common use case for optional is the return value of a function that may fail. As opposed to other approaches, such as std::pair<T,bool>, optional handles expensive-to-construct objects well and is more readable, as the intent is expressed explicitly.




          The if from the example would look a bit more straightforward:



          #include <optional>
          #include <iostream>

          std::optional<int> Foo(bool fail)
          {
          if (!fail) return {42};
          return {};
          }

          void process(bool fail) {
          if (auto val = Foo(fail)) {
          std::cout << val.value() << 'n';
          } else {
          std::cout << "No value!n";
          }
          }

          int main() {
          std::optional<int> oi;
          process(true);
          process(false);
          }


          If you really wished to use Value explicitly then you can always unpack it via reference on a successful branch i.e. auto Value = val.value();



          You need to beware of some caveats. 2 from the top of my head:




          1. Performance: Why is the construction of std::optional<int> more expensive than a std::pair<int, bool>? although for the given example up-to-date clang with -O3 looks pretty convicing


            Note: static was added for process for brevity - to prevent generation of version for external linking.




          2. It will return false if object was default constructed. That might surprise some, default construction of optional doesn't default construct underlying value.


          EDIT:
          After the comments I decided to explicitly state that there isn't anything like type alias for pair<T,bool> or similar compatible with standard library. It's not easy to prove something does not exist, but if there would such a type the standard library would most certainly used it in declaration of insert, it doesn't; hence, I strongly imply that there isn't any semantic wrapper around it.






          share|improve this answer


























          • I think OP is interested in a type alias that works with existing APIs, such as std::map::insert. std::optional obviously doesn’t work here.

            – Konrad Rudolph
            Nov 13 '18 at 15:05











          • std::optional is a pretty good find, thank you. However, I agree with the comment above, a compatibility with existing return types within the standard library itself would be desirable, I didn't think about it initially. Besides, looking at the source code of std::optional, it seems quite heavy-weight for the simple task at hand. So yes, a type alias to std::pair<T,bool> that would be already defined in the standard library, would be the best. Any suggestions?

            – Regus Pregus
            Nov 13 '18 at 15:21











          • @RegusPregus In what way you perceive it heavy? It acutally has less overhead in case of not having a value. pair<bool, T> has to construct an object that is a quite a drawback. IMHO standard library uses pair<bool, T> for historical reasons, i.e. there were no optional before c++17 but that is the idiomatic way now.

            – luk32
            Nov 13 '18 at 16:31











          • @KonradRudolph Yea, but I think the core guideline example is more of a work-around for that fact, rather than an encouragement to use pair<bool, T>. I honestly don't think there are any advantage of pair over optional, unless a particular implementation bites you performance wise. One of interesting implementations is this one which codes no-value as a reserved value of held type. I'd consider it for built-in types to save space, but this is nothing standard.

            – luk32
            Nov 13 '18 at 17:59













          • @RegusPregus Don’t be scared off: std::optional<T> can be incredibly lightweight. Despite the entirely correct caveats in this answer, its implementation can often be as efficient as your std::pair code — subject to library QoI.

            – Konrad Rudolph
            Nov 13 '18 at 19:26





















          1














          You might be interested in the proposed std::expected.



          Its interface follows std::optional pretty closely. The major advantage of
          expected<T, E> over optional<T> is the ability to transport an error:



          enum class errc {err1, err2, err3};

          std::expected<int, errc> Foo()
          {
          if (/* error condition 1 */) return std::unexpected(errc::err1);

          // ... checking other error conditions

          return 42; // no error condition (42 is a good value)
          // implicit conversion from `int` to `expected<int, errc>`
          // avoid boilerplate code
          }

          int main()
          {
          auto q = Foo();

          if (q)
          {
          // Do something with the return value here
          }
          }


          You could also take a look at:





          • Functional exceptionless error-handling with optional and expected;


          • the standard proposal;

          • A possible implementation.




          As a side note main() must return int.






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53283528%2fstandard-template-for-returning-a-value-with-a-boolean-result-flag%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            9














            std::optional is exactly what you are asking about. It's even in the description:




            A common use case for optional is the return value of a function that may fail. As opposed to other approaches, such as std::pair<T,bool>, optional handles expensive-to-construct objects well and is more readable, as the intent is expressed explicitly.




            The if from the example would look a bit more straightforward:



            #include <optional>
            #include <iostream>

            std::optional<int> Foo(bool fail)
            {
            if (!fail) return {42};
            return {};
            }

            void process(bool fail) {
            if (auto val = Foo(fail)) {
            std::cout << val.value() << 'n';
            } else {
            std::cout << "No value!n";
            }
            }

            int main() {
            std::optional<int> oi;
            process(true);
            process(false);
            }


            If you really wished to use Value explicitly then you can always unpack it via reference on a successful branch i.e. auto Value = val.value();



            You need to beware of some caveats. 2 from the top of my head:




            1. Performance: Why is the construction of std::optional<int> more expensive than a std::pair<int, bool>? although for the given example up-to-date clang with -O3 looks pretty convicing


              Note: static was added for process for brevity - to prevent generation of version for external linking.




            2. It will return false if object was default constructed. That might surprise some, default construction of optional doesn't default construct underlying value.


            EDIT:
            After the comments I decided to explicitly state that there isn't anything like type alias for pair<T,bool> or similar compatible with standard library. It's not easy to prove something does not exist, but if there would such a type the standard library would most certainly used it in declaration of insert, it doesn't; hence, I strongly imply that there isn't any semantic wrapper around it.






            share|improve this answer


























            • I think OP is interested in a type alias that works with existing APIs, such as std::map::insert. std::optional obviously doesn’t work here.

              – Konrad Rudolph
              Nov 13 '18 at 15:05











            • std::optional is a pretty good find, thank you. However, I agree with the comment above, a compatibility with existing return types within the standard library itself would be desirable, I didn't think about it initially. Besides, looking at the source code of std::optional, it seems quite heavy-weight for the simple task at hand. So yes, a type alias to std::pair<T,bool> that would be already defined in the standard library, would be the best. Any suggestions?

              – Regus Pregus
              Nov 13 '18 at 15:21











            • @RegusPregus In what way you perceive it heavy? It acutally has less overhead in case of not having a value. pair<bool, T> has to construct an object that is a quite a drawback. IMHO standard library uses pair<bool, T> for historical reasons, i.e. there were no optional before c++17 but that is the idiomatic way now.

              – luk32
              Nov 13 '18 at 16:31











            • @KonradRudolph Yea, but I think the core guideline example is more of a work-around for that fact, rather than an encouragement to use pair<bool, T>. I honestly don't think there are any advantage of pair over optional, unless a particular implementation bites you performance wise. One of interesting implementations is this one which codes no-value as a reserved value of held type. I'd consider it for built-in types to save space, but this is nothing standard.

              – luk32
              Nov 13 '18 at 17:59













            • @RegusPregus Don’t be scared off: std::optional<T> can be incredibly lightweight. Despite the entirely correct caveats in this answer, its implementation can often be as efficient as your std::pair code — subject to library QoI.

              – Konrad Rudolph
              Nov 13 '18 at 19:26


















            9














            std::optional is exactly what you are asking about. It's even in the description:




            A common use case for optional is the return value of a function that may fail. As opposed to other approaches, such as std::pair<T,bool>, optional handles expensive-to-construct objects well and is more readable, as the intent is expressed explicitly.




            The if from the example would look a bit more straightforward:



            #include <optional>
            #include <iostream>

            std::optional<int> Foo(bool fail)
            {
            if (!fail) return {42};
            return {};
            }

            void process(bool fail) {
            if (auto val = Foo(fail)) {
            std::cout << val.value() << 'n';
            } else {
            std::cout << "No value!n";
            }
            }

            int main() {
            std::optional<int> oi;
            process(true);
            process(false);
            }


            If you really wished to use Value explicitly then you can always unpack it via reference on a successful branch i.e. auto Value = val.value();



            You need to beware of some caveats. 2 from the top of my head:




            1. Performance: Why is the construction of std::optional<int> more expensive than a std::pair<int, bool>? although for the given example up-to-date clang with -O3 looks pretty convicing


              Note: static was added for process for brevity - to prevent generation of version for external linking.




            2. It will return false if object was default constructed. That might surprise some, default construction of optional doesn't default construct underlying value.


            EDIT:
            After the comments I decided to explicitly state that there isn't anything like type alias for pair<T,bool> or similar compatible with standard library. It's not easy to prove something does not exist, but if there would such a type the standard library would most certainly used it in declaration of insert, it doesn't; hence, I strongly imply that there isn't any semantic wrapper around it.






            share|improve this answer


























            • I think OP is interested in a type alias that works with existing APIs, such as std::map::insert. std::optional obviously doesn’t work here.

              – Konrad Rudolph
              Nov 13 '18 at 15:05











            • std::optional is a pretty good find, thank you. However, I agree with the comment above, a compatibility with existing return types within the standard library itself would be desirable, I didn't think about it initially. Besides, looking at the source code of std::optional, it seems quite heavy-weight for the simple task at hand. So yes, a type alias to std::pair<T,bool> that would be already defined in the standard library, would be the best. Any suggestions?

              – Regus Pregus
              Nov 13 '18 at 15:21











            • @RegusPregus In what way you perceive it heavy? It acutally has less overhead in case of not having a value. pair<bool, T> has to construct an object that is a quite a drawback. IMHO standard library uses pair<bool, T> for historical reasons, i.e. there were no optional before c++17 but that is the idiomatic way now.

              – luk32
              Nov 13 '18 at 16:31











            • @KonradRudolph Yea, but I think the core guideline example is more of a work-around for that fact, rather than an encouragement to use pair<bool, T>. I honestly don't think there are any advantage of pair over optional, unless a particular implementation bites you performance wise. One of interesting implementations is this one which codes no-value as a reserved value of held type. I'd consider it for built-in types to save space, but this is nothing standard.

              – luk32
              Nov 13 '18 at 17:59













            • @RegusPregus Don’t be scared off: std::optional<T> can be incredibly lightweight. Despite the entirely correct caveats in this answer, its implementation can often be as efficient as your std::pair code — subject to library QoI.

              – Konrad Rudolph
              Nov 13 '18 at 19:26
















            9












            9








            9







            std::optional is exactly what you are asking about. It's even in the description:




            A common use case for optional is the return value of a function that may fail. As opposed to other approaches, such as std::pair<T,bool>, optional handles expensive-to-construct objects well and is more readable, as the intent is expressed explicitly.




            The if from the example would look a bit more straightforward:



            #include <optional>
            #include <iostream>

            std::optional<int> Foo(bool fail)
            {
            if (!fail) return {42};
            return {};
            }

            void process(bool fail) {
            if (auto val = Foo(fail)) {
            std::cout << val.value() << 'n';
            } else {
            std::cout << "No value!n";
            }
            }

            int main() {
            std::optional<int> oi;
            process(true);
            process(false);
            }


            If you really wished to use Value explicitly then you can always unpack it via reference on a successful branch i.e. auto Value = val.value();



            You need to beware of some caveats. 2 from the top of my head:




            1. Performance: Why is the construction of std::optional<int> more expensive than a std::pair<int, bool>? although for the given example up-to-date clang with -O3 looks pretty convicing


              Note: static was added for process for brevity - to prevent generation of version for external linking.




            2. It will return false if object was default constructed. That might surprise some, default construction of optional doesn't default construct underlying value.


            EDIT:
            After the comments I decided to explicitly state that there isn't anything like type alias for pair<T,bool> or similar compatible with standard library. It's not easy to prove something does not exist, but if there would such a type the standard library would most certainly used it in declaration of insert, it doesn't; hence, I strongly imply that there isn't any semantic wrapper around it.






            share|improve this answer















            std::optional is exactly what you are asking about. It's even in the description:




            A common use case for optional is the return value of a function that may fail. As opposed to other approaches, such as std::pair<T,bool>, optional handles expensive-to-construct objects well and is more readable, as the intent is expressed explicitly.




            The if from the example would look a bit more straightforward:



            #include <optional>
            #include <iostream>

            std::optional<int> Foo(bool fail)
            {
            if (!fail) return {42};
            return {};
            }

            void process(bool fail) {
            if (auto val = Foo(fail)) {
            std::cout << val.value() << 'n';
            } else {
            std::cout << "No value!n";
            }
            }

            int main() {
            std::optional<int> oi;
            process(true);
            process(false);
            }


            If you really wished to use Value explicitly then you can always unpack it via reference on a successful branch i.e. auto Value = val.value();



            You need to beware of some caveats. 2 from the top of my head:




            1. Performance: Why is the construction of std::optional<int> more expensive than a std::pair<int, bool>? although for the given example up-to-date clang with -O3 looks pretty convicing


              Note: static was added for process for brevity - to prevent generation of version for external linking.




            2. It will return false if object was default constructed. That might surprise some, default construction of optional doesn't default construct underlying value.


            EDIT:
            After the comments I decided to explicitly state that there isn't anything like type alias for pair<T,bool> or similar compatible with standard library. It's not easy to prove something does not exist, but if there would such a type the standard library would most certainly used it in declaration of insert, it doesn't; hence, I strongly imply that there isn't any semantic wrapper around it.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 13 '18 at 17:28

























            answered Nov 13 '18 at 14:49









            luk32luk32

            12.5k2447




            12.5k2447













            • I think OP is interested in a type alias that works with existing APIs, such as std::map::insert. std::optional obviously doesn’t work here.

              – Konrad Rudolph
              Nov 13 '18 at 15:05











            • std::optional is a pretty good find, thank you. However, I agree with the comment above, a compatibility with existing return types within the standard library itself would be desirable, I didn't think about it initially. Besides, looking at the source code of std::optional, it seems quite heavy-weight for the simple task at hand. So yes, a type alias to std::pair<T,bool> that would be already defined in the standard library, would be the best. Any suggestions?

              – Regus Pregus
              Nov 13 '18 at 15:21











            • @RegusPregus In what way you perceive it heavy? It acutally has less overhead in case of not having a value. pair<bool, T> has to construct an object that is a quite a drawback. IMHO standard library uses pair<bool, T> for historical reasons, i.e. there were no optional before c++17 but that is the idiomatic way now.

              – luk32
              Nov 13 '18 at 16:31











            • @KonradRudolph Yea, but I think the core guideline example is more of a work-around for that fact, rather than an encouragement to use pair<bool, T>. I honestly don't think there are any advantage of pair over optional, unless a particular implementation bites you performance wise. One of interesting implementations is this one which codes no-value as a reserved value of held type. I'd consider it for built-in types to save space, but this is nothing standard.

              – luk32
              Nov 13 '18 at 17:59













            • @RegusPregus Don’t be scared off: std::optional<T> can be incredibly lightweight. Despite the entirely correct caveats in this answer, its implementation can often be as efficient as your std::pair code — subject to library QoI.

              – Konrad Rudolph
              Nov 13 '18 at 19:26





















            • I think OP is interested in a type alias that works with existing APIs, such as std::map::insert. std::optional obviously doesn’t work here.

              – Konrad Rudolph
              Nov 13 '18 at 15:05











            • std::optional is a pretty good find, thank you. However, I agree with the comment above, a compatibility with existing return types within the standard library itself would be desirable, I didn't think about it initially. Besides, looking at the source code of std::optional, it seems quite heavy-weight for the simple task at hand. So yes, a type alias to std::pair<T,bool> that would be already defined in the standard library, would be the best. Any suggestions?

              – Regus Pregus
              Nov 13 '18 at 15:21











            • @RegusPregus In what way you perceive it heavy? It acutally has less overhead in case of not having a value. pair<bool, T> has to construct an object that is a quite a drawback. IMHO standard library uses pair<bool, T> for historical reasons, i.e. there were no optional before c++17 but that is the idiomatic way now.

              – luk32
              Nov 13 '18 at 16:31











            • @KonradRudolph Yea, but I think the core guideline example is more of a work-around for that fact, rather than an encouragement to use pair<bool, T>. I honestly don't think there are any advantage of pair over optional, unless a particular implementation bites you performance wise. One of interesting implementations is this one which codes no-value as a reserved value of held type. I'd consider it for built-in types to save space, but this is nothing standard.

              – luk32
              Nov 13 '18 at 17:59













            • @RegusPregus Don’t be scared off: std::optional<T> can be incredibly lightweight. Despite the entirely correct caveats in this answer, its implementation can often be as efficient as your std::pair code — subject to library QoI.

              – Konrad Rudolph
              Nov 13 '18 at 19:26



















            I think OP is interested in a type alias that works with existing APIs, such as std::map::insert. std::optional obviously doesn’t work here.

            – Konrad Rudolph
            Nov 13 '18 at 15:05





            I think OP is interested in a type alias that works with existing APIs, such as std::map::insert. std::optional obviously doesn’t work here.

            – Konrad Rudolph
            Nov 13 '18 at 15:05













            std::optional is a pretty good find, thank you. However, I agree with the comment above, a compatibility with existing return types within the standard library itself would be desirable, I didn't think about it initially. Besides, looking at the source code of std::optional, it seems quite heavy-weight for the simple task at hand. So yes, a type alias to std::pair<T,bool> that would be already defined in the standard library, would be the best. Any suggestions?

            – Regus Pregus
            Nov 13 '18 at 15:21





            std::optional is a pretty good find, thank you. However, I agree with the comment above, a compatibility with existing return types within the standard library itself would be desirable, I didn't think about it initially. Besides, looking at the source code of std::optional, it seems quite heavy-weight for the simple task at hand. So yes, a type alias to std::pair<T,bool> that would be already defined in the standard library, would be the best. Any suggestions?

            – Regus Pregus
            Nov 13 '18 at 15:21













            @RegusPregus In what way you perceive it heavy? It acutally has less overhead in case of not having a value. pair<bool, T> has to construct an object that is a quite a drawback. IMHO standard library uses pair<bool, T> for historical reasons, i.e. there were no optional before c++17 but that is the idiomatic way now.

            – luk32
            Nov 13 '18 at 16:31





            @RegusPregus In what way you perceive it heavy? It acutally has less overhead in case of not having a value. pair<bool, T> has to construct an object that is a quite a drawback. IMHO standard library uses pair<bool, T> for historical reasons, i.e. there were no optional before c++17 but that is the idiomatic way now.

            – luk32
            Nov 13 '18 at 16:31













            @KonradRudolph Yea, but I think the core guideline example is more of a work-around for that fact, rather than an encouragement to use pair<bool, T>. I honestly don't think there are any advantage of pair over optional, unless a particular implementation bites you performance wise. One of interesting implementations is this one which codes no-value as a reserved value of held type. I'd consider it for built-in types to save space, but this is nothing standard.

            – luk32
            Nov 13 '18 at 17:59







            @KonradRudolph Yea, but I think the core guideline example is more of a work-around for that fact, rather than an encouragement to use pair<bool, T>. I honestly don't think there are any advantage of pair over optional, unless a particular implementation bites you performance wise. One of interesting implementations is this one which codes no-value as a reserved value of held type. I'd consider it for built-in types to save space, but this is nothing standard.

            – luk32
            Nov 13 '18 at 17:59















            @RegusPregus Don’t be scared off: std::optional<T> can be incredibly lightweight. Despite the entirely correct caveats in this answer, its implementation can often be as efficient as your std::pair code — subject to library QoI.

            – Konrad Rudolph
            Nov 13 '18 at 19:26







            @RegusPregus Don’t be scared off: std::optional<T> can be incredibly lightweight. Despite the entirely correct caveats in this answer, its implementation can often be as efficient as your std::pair code — subject to library QoI.

            – Konrad Rudolph
            Nov 13 '18 at 19:26















            1














            You might be interested in the proposed std::expected.



            Its interface follows std::optional pretty closely. The major advantage of
            expected<T, E> over optional<T> is the ability to transport an error:



            enum class errc {err1, err2, err3};

            std::expected<int, errc> Foo()
            {
            if (/* error condition 1 */) return std::unexpected(errc::err1);

            // ... checking other error conditions

            return 42; // no error condition (42 is a good value)
            // implicit conversion from `int` to `expected<int, errc>`
            // avoid boilerplate code
            }

            int main()
            {
            auto q = Foo();

            if (q)
            {
            // Do something with the return value here
            }
            }


            You could also take a look at:





            • Functional exceptionless error-handling with optional and expected;


            • the standard proposal;

            • A possible implementation.




            As a side note main() must return int.






            share|improve this answer




























              1














              You might be interested in the proposed std::expected.



              Its interface follows std::optional pretty closely. The major advantage of
              expected<T, E> over optional<T> is the ability to transport an error:



              enum class errc {err1, err2, err3};

              std::expected<int, errc> Foo()
              {
              if (/* error condition 1 */) return std::unexpected(errc::err1);

              // ... checking other error conditions

              return 42; // no error condition (42 is a good value)
              // implicit conversion from `int` to `expected<int, errc>`
              // avoid boilerplate code
              }

              int main()
              {
              auto q = Foo();

              if (q)
              {
              // Do something with the return value here
              }
              }


              You could also take a look at:





              • Functional exceptionless error-handling with optional and expected;


              • the standard proposal;

              • A possible implementation.




              As a side note main() must return int.






              share|improve this answer


























                1












                1








                1







                You might be interested in the proposed std::expected.



                Its interface follows std::optional pretty closely. The major advantage of
                expected<T, E> over optional<T> is the ability to transport an error:



                enum class errc {err1, err2, err3};

                std::expected<int, errc> Foo()
                {
                if (/* error condition 1 */) return std::unexpected(errc::err1);

                // ... checking other error conditions

                return 42; // no error condition (42 is a good value)
                // implicit conversion from `int` to `expected<int, errc>`
                // avoid boilerplate code
                }

                int main()
                {
                auto q = Foo();

                if (q)
                {
                // Do something with the return value here
                }
                }


                You could also take a look at:





                • Functional exceptionless error-handling with optional and expected;


                • the standard proposal;

                • A possible implementation.




                As a side note main() must return int.






                share|improve this answer













                You might be interested in the proposed std::expected.



                Its interface follows std::optional pretty closely. The major advantage of
                expected<T, E> over optional<T> is the ability to transport an error:



                enum class errc {err1, err2, err3};

                std::expected<int, errc> Foo()
                {
                if (/* error condition 1 */) return std::unexpected(errc::err1);

                // ... checking other error conditions

                return 42; // no error condition (42 is a good value)
                // implicit conversion from `int` to `expected<int, errc>`
                // avoid boilerplate code
                }

                int main()
                {
                auto q = Foo();

                if (q)
                {
                // Do something with the return value here
                }
                }


                You could also take a look at:





                • Functional exceptionless error-handling with optional and expected;


                • the standard proposal;

                • A possible implementation.




                As a side note main() must return int.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 14 '18 at 9:51









                manliomanlio

                13.9k104780




                13.9k104780






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53283528%2fstandard-template-for-returning-a-value-with-a-boolean-result-flag%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    這個網誌中的熱門文章

                    Xamarin.form Move up view when keyboard appear

                    Post-Redirect-Get with Spring WebFlux and Thymeleaf

                    Anylogic : not able to use stopDelay()