[英]How to printf std::vector<>::size_type?
std::vector
有一个成员类型size_type
。 它的 printf 格式说明符是什么?
请注意, size_type
与size_t
不同。
https://en.cppreference.com/w/cpp/container/vector
https://en.cppreference.com/w/cpp/types/size_t
https://en.cppreference.com/w/cpp/io/c/fprintf
它的 printf 格式说明符是什么?
没人知道。 它没有指定std::vector<?>::size_type
到底是什么,除了它是一个“unsigned integer type”int C++ Container Library, General container requirements 。 因为printf
格式说明符取决于类型,所以这一切都取决于特定的实现。 也可能不存在printf
格式说明符。
如何 printf std::vector<>::size_type?
步骤:
printf
格式说明符。 无论如何,它与std::cout::operator<<
重载为打印所做的一样。 只是:
#include <cstdlib>
#include <string>
#include <cstdio>
#include <vector>
template<typename T> constexpr const char *get_printf_formatting_spec() noexcept;
template<> constexpr const char *get_printf_formatting_spec<std::size_t>() noexcept {
return "zu";
}
template<> constexpr const char *get_printf_formatting_spec<unsigned long long>() noexcept {
return "llu";
}
/// etc.
int main() {
const auto fmt = std::string() +
"%" +
get_printf_formatting_spec<std::vector<int>::size_type>() +
"\n";
std::printf(fmt.c_str(), static_cast<std::vector<int>::size_type>(1));
}
一个不起眼的实用技巧
正如其他答案所建议的那样,似乎没有优雅、直接的方法来做到这一点。 那怎么办? 由于缺乏更好的方法,让我们谦虚 go 回到基础:
std::is_signed_t<T>
确定向量size_type
的符号。size_type
转换为适当的 integer 类型。PS - 要在有符号/无符号格式说明符之间进行选择,您需要动态构造格式字符串,或者在两个格式字符串之间进行选择,或者使用条件编译等。相反,对于最大的有符号类型,您可以只使用 go 并始终强制转换进入那个- 以需要最后一点的最大尺寸失败为代价。
在printf
中使用的选项是%zu
。
这是从 C99 使用的。 在您需要将类型转换为unsigned long
之前。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.