You can delegate a function:
template <typename T> std::string stream(const T& x) { std::ostringstream ss; ss << x; return ss.str(); } throw std::runtime_error("Error..." + stream(x));
What boost::lexical_cast also means:
throw std::runtime_error("Error..." + boost::lexical_cast<std::string>(x));
Or you can use a temporary stream, which includes the need to do a translation, since operator<< usually returns only basic_ostream<char>& :
throw std::runtime_error( static_cast<std::ostringstream&&>(std::ostringstream{} << "Error..." << x) .str() );
Or you can wrap this logic in a separate type, which when streaming converts the result to string , for fun:
struct ToStrT { friend std::string operator<<(std::ostream& os, ToStrT ) { return static_cast<std::ostringstream&&>(os).str(); } }; constexpr ToStrT ToStr{}; throw std::runtime_error(std::ostringstream{} << "Error..." << x << ToStr);
Barry source share