私が試したこと:
class MyException : public std::runtime_error {};
throw MyException("Sorry out of bounds, should be between 0 and "+limit);
そのような機能をどのように実装できるかわかりません。
文字列を受け取り、それを std::runtime_error のコンストラクターに送信する MyException のコンストラクター関数を定義する必要があります。このようなもの:
class MyException : public std::runtime_error {
public:
MyException(std::string str) : std::runtime_error(str)
{
}
};
ここには 2 つの問題があります。例外で文字列パラメーターを受け入れる方法と、ランタイム情報から文字列を作成する方法です。
class MyException : public std::runtime_error
{
MyExcetion(const std::string& message) // pass by const reference, to avoid unnecessary copying
: std::runtime_error(message)
{}
};
次に、文字列引数を構築するさまざまな方法があります。
std::to_string
is most convenient, but is a C++11 function.
throw MyException(std::string("Out of bounds, should be between 0 and ")
+ std::to_string(limit));
Or use boost::lexical_cast
(function name is a link).
throw MyException(std::string("Out of bounds, should be between 0 and ")
+ boost::lexical_cast<std::string>(limit));
You could also create a C-string buffer and use a printf style command. std::snprintf
would be preferred, but is also C++11.
char buffer[24];
int retval = std::sprintf(buffer, "%d", limit); // not preferred
// could check that retval is positive
throw MyException(std::string("Out of bounds, should be between 0 and ")
+ buffer);