比较类型字节大小的编译器宏



这个if语句可以用#if ....宏替换吗?
可能不需要包含(太多)额外的头。

#include <cstdint>
#include <string>
///Parse a string to obtain a fixed width type
inline uint64_t stou64(const std::string& in) {
if (sizeof(unsigned long) == sizeof(uint64_t)) {
return std::stoul(in);
} else {
return std::stoull(in);
}
}

您不需要预处理宏。无论大小如何,函数都是定义良好的,编译器足够聪明,可以将未使用的分支完全优化掉。

如果您想确保即使禁用了优化也可以删除未使用的分支,您可以使用If constexpr。在您的示例中,只需在if后面添加constexpr


如果您不需要支持当前活动的区域设置,则考虑使用std::from_chars代替。

我更喜欢这种方法(在c++ 17std::from_chars之前):

template<typename T>
T string_to(const std::string& in);
template<>
int string_to<int>(const std::string& in) {
return std::stoi(in);
}
template<>
unsigned string_to<unsigned>(const std::string& in) {
return std::stol(in);
}
template<>
long string_to<long>(const std::string& in) {
return std::stol(in);
}
template<>
long long string_to<long long>(const std::string& in) {
return std::stoll(in);
}
template<>
unsigned long string_to<unsigned long>(const std::string& in) {
return std::stoul(in);
}
template<>
unsigned long long string_to<unsigned long long>(const std::string& in) {
return std::stoull(in);
}
inline uint64_t stou64(const std::string& in) {
return string_to<uint64_t>(in);
}

https://godbolt.org/z/T57cbq91z

不,您的if语句是不同的,因为if和else路径都被编译并且必须是有效的表达式,即使编译器然后优化代码仅采取的路径。在#if宏中,编译器只能看到剩余的部分。被删除的部分不必对给定的参数有意义。

由于这在模板中可能是一个问题,因此在c++17中添加了constexpr if语法。

#include <cstdint>
#include <string>
///Parse a string to obtain a fixed width type
inline uint64_t stou64(const std::string& in) {
if constexpr (sizeof(unsigned long) == sizeof(uint64_t)) {
return std::stoul(in);
} else {
return std::stoull(in);
}
}

注意:在这个特定的例子中,这无关紧要。但是为什么不习惯if constexpr呢?

最新更新