简体   繁体   中英

Removing the void specializations for std::future and std::promise

With regards to the paper which describes removing the void specializations for std::future and std::promise P0241R0 . This may be a stupid question but the proposed solution is to remove the void specialization entirely, but then what are people expected to do when they want to instantiate a std::future<void> object?

As noted in the reference, this would be possible if void were a regular type .

void get_value() {
    void x;
    return x;
}

This is the way it works in some other languages, so it's not without precedent. In other languages it's called the "unit" type, because it has exactly one possible value. (Other languages also have the "null" type, which has no possible values, so if you try to create one you get an error. It's named "null" but it's unrelated to null pointers.)

Having tinkered with implementing the TS, it seems possible to avoid specializing for void if the implementation does some clever things with enable_if, eg

template <class R>
R future<R>::get()
{
  return shared().get();
}

template <class R>
class shared_state {
  ...
  R get()
  {
    wait();
    if constexpr (!std::is_same_v<V, void>) {
      return *_value;
    }
  }

  template <typename V = value_t, std::enable_if_t<!std::is_same_v<V, void>, V>* = nullptr>
  void set_value(const V& value)
  {
    ...
  }

  template <typename V = value_t, std::enable_if_t<std::is_same_v<V, void>, V>* = nullptr>
  void set_value()
  {
    ...
  }
}

The purpose of a std::future is to know when a process with no actual value to return has ended. So basically it's a synchronization tool.

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