3 ms·
C++ has both return type polymorphism and inheritance. What it doesn't have is the kind of type inference that Haskell has. Its type inference is very limited.
by Maxatar 2y ago
C++ has both return type polymorphism and inheritance. What it doesn't have is the kind of type inference that Haskell has. Its type inference is very limited.
- fooker 2y agoYou can't have two functions that differ in just the return type in C++
- slaymaker1907 2y agoYou 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; }
- account42 2y agoThat's not polymorphism as that template parameter won't be deduced in any context and you will always have to explicitly instantiate the template.
- Maxatar 2y agoThat 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.
- gpderetta 2y agochallenge accepted: https://gcc.godbolt.org/z/bGdP79aEj https://gcc.godbolt.org/z/bGdP79aEj edit: you get pseudo call-by-name as a bonus.
- pritambaral 2y agoYou 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 https://cppinsights.io/s/f0b9976f
- Maxatar 2y agoYou 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.