Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C++ have a unit type?

Tags:

c++

unit-type

I know that the C++ standard library has a unit type - I've seen it before - but I can't remember what it's called. It starts with an "m", I know that much, and it is equivalent to this definition:

struct Unit {};

Basically, a unit type is a type with only one distinct value - as contrasted with void which has zero values and bool which has two.


If you must know, my particular use case was regarding the constructors of a template class with a union member. It pretty much looks like this:

template<typename T>
struct foo {
    union {
        T t;
        std::string str;
    } data;
    foo(T const& t) {
        data.t = t;
    }
    foo(std::monostate unused, std::string const& str) {
        data.str = str;
    }
};

In order to be able to distinguish the two constructors from one another, should T be equal to std::string, a sentry argument in the second constructor is needed. void won't work of course, and bool wouldn't make sense because there would be no difference between passing in true vs false - what was needed was a unit type.

like image 586
jcarpenter2 Avatar asked Apr 19 '18 00:04

jcarpenter2


2 Answers

It's called std::monostate (Since C++17). It also overloads the == operator to return true, as well as some other operators, so that all instances of std::monostate are equal.

like image 185
jcarpenter2 Avatar answered Sep 18 '22 17:09

jcarpenter2


C++ has arbitrarily many unit types, including

  • std::nullptr_t
  • std::monostate
  • std::tuple<>
  • struct unit {};
like image 36
Caleth Avatar answered Sep 17 '22 17:09

Caleth