Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
#include <boost/format.hpp>
class MakeString2 {
public:
MakeString2(const char* fmt): m_fmt(fmt) {}
template<class T>
MakeString2& operator<< (const T& arg) {
m_fmt % arg;
return *this;
}
operator std::string() const {
return m_fmt.str();
}
protected:
boost::format m_fmt;
};
void func(int id, const std::string& data1, const std::string& data2)
{
throw std::runtime_error(MakeString2("Operation with id = %1% failed, because data1 (%2%) is incompatible with data2 (%3%)") << id << data1 << data2);
}
void func(int id, const std::string& data1, const std::string& data2)
{
throw std::runtime_error("Operation with id = " + boost::lexical_cast<std::string>(id) + " failed, because data1 (" + data1 + ") is incompatible with data2 (" + data2 + ")");
}
void func(int id, const A& data1, const B& data2)
{
throw std::runtime_error(std::string("Operation with id = ") + boost::lexical_cast<std::string>(id) + " failed, because data1 (" + boost::lexical_cast<std::string>(data1) + ") is incompatible with data2 (" + boost::lexical_cast<std::string>(data2) + ")");
}
void func(int id, const A& data1, const B& data2)
{
throw std::runtime_error(MakeString() << "Operation with id = " << id << " failed, because data1 (" << data1 << ") is incompatible with data2 (" << data2 << ")");
}
Угу. Только нужно первый строковый операнд ещё принудительно привести к std::string, т.к. для const char* не определен оператор "+".Не нужно, я же проверил на компилябельность перед отправкой комментария.
Не нужно, я же проверил на компилябельность перед отправкой комментария.
Ну а так, для составления сложных строк уже придуман упомянутый выше boost::format, его можно научить и с пользовательскими типами работать.
std::cout << boost::format("%2% - %1%") % 1 % 2 << std::endl; // работает
...
boost::format fmt("%2% - %1%");
fmt % 1 % 2;
std::string str = fmt.str() // работает
...
boost::format fmt("%2% - %1%");
std::string str = fmt % 1 % 2; // не работает
...
std::string str = boost::format("%2% - %1%") % 1 % 2; // не работает
...
throw std::runtime_error(boost::format("%2% - %1%") % 1 % 2); // не работает
...
std::string str = MakeString2("%2% - %1%") << 1 << 2; // работает (MakeString2 определен в моем комментарии выше)
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
class LogMessage
{
public:
~LogMessage()
{
cout << msg << endl;
}
static LogMessage log()
{
return LogMessage();
}
template<class T>
LogMessage& operator<<(const T& obj)
{
std::ostringstream ostr;
ostr << obj;
if(!msg.empty())
msg+=" ";
msg+=ostr.str();
return *this;
}
private:
LogMessage(){};
std::string msg;
};
LogMessage log()
{
return LogMessage::log();
}
struct Custom
{
Custom():x(33), name("some_obj"){}
int x;
std::string name;
};
std::ostream& operator<< (std::ostream& ostr, const Custom& obj)
{
return ostr << "x="<<obj.x<<", name: " << obj.name;
}
int main()
{
log() << "hey" << 33;
Custom customObject;
customObject.x = 37;
log() << 3.4 << " and " << customObject;
}
#define STR(WHAT) ({std::stringstream e;e<<WHAT;e.str();})throw runtime_error(STR("2+2="<<5));
std::stringstream и форматирование строк