Nullable values in C++

后端 未结 4 1006
一整个雨季
一整个雨季 2020-12-01 17:48

I\'m creating a database access layer in native C++, and I\'m looking at ways to support NULL values. Here is what I have so far:

class CNullValue
{
public:         


        
4条回答
  •  醉话见心
    2020-12-01 18:19

    There are lot of Nullable type implementation for C++ and most are incomplete. In C++ world, nullable types are called optional types. This was proposed for C++14 but got postponed. However the code to implement it compiles and works on most C++11 compilers. You can just drop in the single header file implementing optional type and start using it:

    https://raw.githubusercontent.com/akrzemi1/Optional/master/optional.hpp

    Sample usage:

    #if (defined __cplusplus) && (__cplusplus >= 201700L)
    #include 
    #else
    #include "optional.hpp"
    #endif
    
    #include 
    
    #if (defined __cplusplus) && (__cplusplus >= 201700L)
    using std::optional;
    #else
    using std::experimental::optional;
    #endif
    
    int main()
    {
        optional o1,      // empty
                      o2 = 1,  // init from rvalue
                      o3 = o2; // copy-constructor
    
        if (!o1) {
            cout << "o1 has no value";
        } 
    
        std::cout << *o2 << ' ' << *o3 << ' ' << *o4 << '\n';
    }
    

    More documentation: http://en.cppreference.com/w/cpp/experimental/optional

    Also see my other answer: https://stackoverflow.com/a/37624595/207661

提交回复
热议问题