It depends on what you are trying to accomplish, but there are many possibilities for this. Here are some of them that come to mind:
If one of the defined list of return types is defined inside the function:
Since you edited your question, this looks like what you want. You can try boost::variant :
boost::variant<int, double, std::string> foo() { if (something) //set type to int else if (something else) //set type to double else //set type to std::string }
If the return type depends on the template argument:
You can use SFINAE to control overload resolution:
template<typename T, typename = typename std::enable_if<std::is_integral<T>::value, T>::type> std::vector<int> foo() {...} template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type> std::vector<std::string> foo() {...}
If the return type can be any:
A boost::any will work fine:
boost::any foo() {...}
If the return type is always inferred from a particular class:
Returns a smart pointer to the base class:
std::unique_ptr<Base> foo() { if (something) return std::unique_ptr<Base>{new Derived1}; if (something else) return std::unique_ptr<Base>{new Derived2}; }
source share