Hacker News new | ask | show | jobs
by mFixman 698 days ago
> I think it's not correct to say that void is a monotype in C++, because the compiler won't allow you to assign the result of a function marked void to a variable, and you cannot declare a variable of type void.

The compiler does not allow you to do that particular operation out of an arbitrary restriction, but that does not make `void` a true void type. It still holds a monotype value!

  int bar() {
      std::cout << "Bar" << std::endl;
      return 0;
  }
  
  void baz() {
      std::cout << "Baz" << std::endl;
  }
  
  template <typename T> T foo(T (*f)()) {
      std::cout << "Foo" << std::endl;
      return f();
  }
  
  template <typename T> T varfoo(T (*f)()) {
      std::cout << "Varfoo" << std::endl;
      T a = f();
      return a;
  }
  
  int main()
  {
      foo(bar); // Valid (returning an int).
      foo(baz); // Valid (returning a void).
      varfoo(bar); // Valid (assigning an int).
      // varfoo(baz); // Invalid (assigning a void (why???)).
  }