Hacker News new | ask | show | jobs
by fooker 722 days ago
You can't have two functions that differ in just the return type in C++
3 comments

You can sort of do it so long as the return type is a template parameter.

    template<typename T>
    T my_construct() { T result; return result; }
That's not polymorphism as that template parameter won't be deduced in any context and you will always have to explicitly instantiate the template.
That is still polymorphic, but as I mentioned C++ does not do the kind of type deduction that Haskell supports so you do have to explicitly instantiate the template. However, you can instantiate it based on context, for example using decltype.
challenge accepted: https://gcc.godbolt.org/z/bGdP79aEj

edit: you get pseudo call-by-name as a bonus.

You certainly can and I know there are several JSON libraries that do it. The gist of it is to write a struct and overload the conversion operator for the set of return types you want to support, for example overload the conversion operator to int and std::string. As soon as the instance of that struct is used in a context that needs an std::string, then it calls the string overload.
You can, if you abuse C++ enough. I needed this very thing for a custom DSL.

    struct PolyReturn {
      const int value;
      operator int() const { return value; }
      operator bool() const { return value > 0; }
    };

https://cppinsights.io/s/f0b9976f