简体   繁体   中英

Does C++ have a 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.

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.

C++有任意多种单元类型,包括

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM