此代码片段(https://gcc.godbolt.org/z/hKDMxm):
#include <iostream>
#include <sstream>
using namespace std;
int main() {
auto s = (ostringstream{} << "string").str();
cout << s;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
使用 msvc 编译并按预期运行,但无法使用 clang 9.0.0 和 gcc 9.2 进行编译,并给出以下错误消息:no member named 'str' in 'std::basic_ostream<char>'。查看https://en.cppreference.com/w/cpp/io/basic_ostringstream/str显然str()有ostringstream. 为什么 clang 和 gcc 无法编译此代码?
类似于这个问题。需要使用类似 printf 的风格而不是字符串串联或 iostreams 来抛出异常和消息。使用 C++ 20 格式化库:
throw std::runtime_error {
std::format("Critical error! Code {}: {}", errno, strerror(errno))
};
Run Code Online (Sandbox Code Playgroud)
但在所有带有格式化的异常中,感觉调用格式都不符合人体工学,可以变得更好吗?