在(重新)实现一个简单的 constexpr 映射时,我写了这个(godbolt):
template <class key_type, class value_type, int N>
class flat_map
{
private:
struct pair
{
key_type key;
value_type value;
};
const pair elements[N];
public:
consteval flat_map(const pair (&arr)[N]) noexcept
: elements(arr) // works on gcc?!
{}
[[nodiscard]] consteval value_type operator[](const key_type key) const
{
for (const pair &elem : elements)
if (elem.key == key)
return elem.value;
throw "Key not found";
}
};
constexpr flat_map<int, char, 3> m = {{
{ 4, 'a' }, { -1, 'b' …Run Code Online (Sandbox Code Playgroud) 考虑这个片段:
#include <iostream>
#include <string>
#include <string_view>
using namespace std::literals;
class A
{
public:
std::string to_string() const noexcept
{
return "hey"; // "hey"s
}
std::string_view to_stringview() const noexcept
{
return "hello"; // "hello"sv
}
};
int main()
{
A a;
std::cout << "The class says: " << a.to_string() << '\n';
std::cout << "The class says: " << a.to_stringview() << '\n';
}
Run Code Online (Sandbox Code Playgroud)
我天真地期待一些警告,to_stringview()比如返回本地临时的引用,但 g++ 和 clang 都没有说什么,所以这段代码看起来合法并且有效。
由于这会产生预期的警告:
const std::string& to_string() const noexcept
{
return …Run Code Online (Sandbox Code Playgroud) 迈出使用库的第一步<chrono>,我从日常的基本算术开始time_point。感谢 @HowardHinnant 的一篇非常有用的帖子,我成功地写了这个:
#include <chrono>
using namespace std::chrono_literals;
int main()
{
std::chrono::sys_days d {std::chrono::January/31/2022};
d += std::chrono::days{2}; // ok
//d += 48h; // error: no match for 'operator+=' with std::chrono::hours
}
Run Code Online (Sandbox Code Playgroud)
我不清楚的是为什么d += 48h;不允许。需要std::chrono::time_point<>::operator+=a duration,该表达式中的右值std::chrono::hours是 a在我看来代表持续时间。这里的哲学是什么?根据度量单位是否有不同的持续时间类型必须与粒度兼容time_point?为什么?
另一方面,我理解为什么d += 2d;会给出错误,因为在本例中std::literals::chrono_literals::operator""d
是 a std::chrono::day,它不是持续时间(这很容易形成日期文字,尽管对我来说似乎有点不一致)。我想知道是否有更方便的方法来表达相当于 的持续时间文字std::chrono::days{2}。
我正在使用这样的函数来导出 xml 文件中的数据(注意:愚蠢的例子):
void write_xml_file(const std::string& path)
{
using namespace std::string_view_literals; // Use "..."sv
FileWrite f(path);
f<< "<root>\n"sv
<< "\t<nested1>\n"sv
<< "\t\t<nested2>\n"sv
<< "\t\t\t<nested3>\n"sv
<< "\t\t\t\t<nested4>\n"sv;
//...
}
Run Code Online (Sandbox Code Playgroud)
如果这些<<需要std::string_view的参数:
FileWrite& FileWrite::operator<<(const std::string_view s) const noexcept
{
fwrite(s.data(), sizeof(char), s.length(), /* FILE* */ f);
return *this;
}
Run Code Online (Sandbox Code Playgroud)
如有必要,我可以添加重载std::string, std::array, ...
现在,我真的很想像这样写上面的内容:
// Create a compile-time "\t\t\t..."sv
consteval std::string_view indent(const std::size_t n) { /* meh? */ }
void write_xml_file(const std::string& path)
{
using namespace std::string_view_literals; …Run Code Online (Sandbox Code Playgroud) c++ ×4
c++20 ×2
string-view ×2
arrays ×1
c++-chrono ×1
compile-time ×1
consteval ×1
duration ×1
lifetime ×1
literals ×1
return ×1