我刚刚阅读了 Raymond Chen 出色的“旧新事物”中的以下文章: https://devblogs.microsoft.com/oldnewthing/20210719-00/ ?p=105454
我对此有一个疑问,最好在以下代码片段中进行描述。为什么'x3'的初始化是被允许的?我没有看到下面“x2”和“x3”的初始化之间有任何语义差异。
#include <memory>
class X
{
struct PrivateTag {}; // default constructor is *NOT* explicit
public:
X(PrivateTag) {}
static auto Create() -> std::unique_ptr<X>
{
return std::make_unique<X>(PrivateTag{});
}
};
int main()
{
auto x1 = X::Create(); // ok: proper way to create this
//auto x2 = X(X::PrivateTag{}); // error: cannot access private struct
auto x3 = X({}); // ok: why ?!
}
Run Code Online (Sandbox Code Playgroud) 注意:这个问题使用C++20,我使用的是Visual Studio 2022 (v17.2.2)。
我想创建一个模板函数包装器以允许我使用 std::format 样式日志记录。包装函数最终将执行一些其他与格式无关的操作,这些操作在这里并不重要。
请参考下面的代码。请注意,Log1()工作正常,但使用起来感觉很笨拙。 Log2()没问题,但使用std::vformat()会丢失日志格式字符串的编译时检查。
我真正想做的是Log3()。问题是 Visual Studio (v17.2.2) 不喜欢这样。
有什么方法可以让它工作(没有宏)?
#include <iostream>
#include <format>
#include <string_view>
// works fine: usage is clunky
auto Log1(std::string_view sv)
{
std::cout << sv;
}
// works, but fmt string is checked at runtime - not compile time
template<typename... Args>
auto Log2(std::string_view fmt, Args&&... args)
{
std::cout << std::vformat(fmt, std::make_format_args(args...));
}
// this doesn't work
template<typename... Args>
auto Log3(std::string_view fmt, Args&&... args)
{ …Run Code Online (Sandbox Code Playgroud)