c++boostboost-variant

Define boost variant type to pass explicitly empty values


I want to have boost::variant with empty state. So I define a boost::variant with boost::blank as the first alternative. But then I want to pass this as function parameter:

void f(Variant v);
...
void g()
{
   f(boost::blank{});
}

It does not look nice due to braces. Seem to be better if it accepted boost::none:

void g()
{
   f(boost::none);
}

But I don't think I have seen boost::variant<boost::none_t, ...> anywhere. boost::none_t is a satellite of boost::optional. Is it fine to use with boost::variant?


Solution

  • You can just default construct, which will initialize the first element type.

    Alternatively you can define your own constant of type boost::blank:

    Live On Wandbox

    #include <boost/variant.hpp>
    #include <iostream>
    
    using Variant = boost::variant<
        boost::blank,
        int,
        std::string>;
    
    void foo(Variant v = {}) {
        std::cout << "foo: " << v.which() << "\n";
    }
    
    int main()
    {
        foo();
        foo({});
        foo(Variant{});
        foo(boost::blank{});
        
        static constexpr boost::blank blank;
        foo(blank);
        
        foo(42);
        foo("LtUaE");
    }
    

    Prints

    foo: 0
    foo: 0
    foo: 0
    foo: 0
    foo: 0
    foo: 1
    foo: 2