例如,我的代码是由c++20标准的编译器编译的。同时,它使用一个库(不仅仅是头文件),使用相同的编译器编译,但使用 C++17 标准。安全吗?
主页
/
user-591545
borg's questions
有一定的自定义类型。我想检查代码是否已为其定义std::formatter,然后使用它将其转换为字符串,如果没有,则打印硬编码字符串。是否可以做到这一点(最好在编译时)?
struct A{};
if (there_is_formatter()) {
std::print("{}", A{});
} else {
std::print("no formatter");
}
我想得到这种行为,以便每个宏参数都包含在一些代码中。例如,打印每个参数:
#define print_all(...) /* magic */
print_all(1, 2, "123"); // calls std::cout << 1; std::cout << 2; std::cout << "123";
我需要编写一个宏,它的行为会根据是否给出 1 个参数或 2+ 个参数而有所不同。如何才能做到这一点?我看到解决方案列出了一堆宏(对于 2、对于 3、对于 4 等参数),但我想找到一个没有这个的解决方案
#define MACRO_WITH_1_ARG(arg) /* impl 1 */
#define MACRO_WITH_N_ARGS(...) /* impl 2 */
#define MACRO(...) /* magic */
MACRO("test"); // calls 1
MACRO("test", 42); // calls 2
我注意到我可以传递一个空参数而不是宏参数的普通参数。在这种情况下是否可以通过生成编译错误来防止这种行为?
#define AtLeastOneArg(arg, ...) arg
int main() {
AtLeastOneArg(;, ;); // compiles - OK
AtLeastOneArg(;); // compiles - OK
AtLeastOneArg(); // compiles - unexpected
}
在专业化中使用不完整类型(不在标头中而是在源代码中定义它们)是否有效?以下示例可以编译,但我不确定是否可行
struct A;
namespace fmt{
template<>
struct formatter<A> : formatter<int> {
auto format(A a, format_context& ctx) const;
};
}
struct A {
int x=42;
};
namespace fmt{
auto formatter<A>::format(A a, format_context& ctx) const {
return formatter<int>::format(a.x, ctx);
}
}