Advantages of an empty class in C++

后端 未结 9 1550
夕颜
夕颜 2020-12-08 20:51

What could be the possible advantages/uses of having an empty class?

P.S: This question might sound trivial to some of you but it is just for learning purpose and h

9条回答
  •  囚心锁ツ
    2020-12-08 21:37

    The following can be used to have a boost::variant which can hold an (SQL) NULL value for example.

    class Null { };
    
    typedef boost::variant Value;
    

    To make it more useful things like operator== and operator<< are handy. For example:

    std::ostream& operator<<(std::ostream &lhs, const Null &rhs)
    {
         lhs << "*NULL*";
         return lhs;
    }
    
    int main()
    {
        Variant v("hello");
        std::cout << v << std::endl;
        v = Null();
        std::cout << v << std::endl;
        ...
    }
    

    Will give:

    hello
    *NULL*
    

提交回复
热议问题